gpt4 book ai didi

c# - 主要方法代码完全在 try/catch : Is it bad practice? 中

转载 作者:IT王子 更新时间:2023-10-29 04:09:23 25 4
gpt4 key购买 nike

通常我将所有 Main 方法代码放在一个 try/catch block 中,如下所示:

public static void Main(string[] args)
{
try
{
// code
}
catch (Exception e)
{
// code
}
}

我这样做是为了防止任何异常设法从其余的程序逻辑中溜走,从而允许我对此做一些事情,比如将它显示到控制台,将它记录到一个文件等。但是,我已被告知这是不好的做法。

你认为这是不好的做法吗?

最佳答案

在没有充分理由的情况下将任何代码段包装在try/catch block 中是不好的做法。

在 .NET 编程模型中,应为真正的异常情况或条件保留异常。您应该 try catch 您实际上可以做某事的异常。此外,您不应该永远捕获System.Exception基类(而是更愿意捕获可以的更具体的派生异常类)处理)。如果在程序执行过程中遇到真正意外的异常,您实际上应该崩溃。

显然,“正确”答案必须根据具体情况做出,具体取决于 catch 中的 //code 占位符内部发生的情况> 阻止。但是,如果您要求一般规则或“最佳实践”,您应该始终有一个特定的理由来捕获异常,而不仅仅是将所有代码包装在一个巨大的 try/catch 中想都没想就理所当然地屏蔽

请注意,如果您只是为了记录或报告错误而试图捕获任何可能发生的未处理异常,您应该使用 AppDomain.UnhandledException event .这是一个仅通知事件,因此它不允许您处理那些异常,但它是在您的应用程序崩溃后实现日志记录或错误报告功能的正确位置。


编辑:当我正在阅读 Raymond Chen 的优秀博客时,"The Old New Thing" , 我注意到他最近发表了一篇关于类似主题的文章。它特定于 COM,而不是 .NET Framework,但有关错误处理的一般概念同样适用于这两种环境。我想我会在这里分享这篇文章中的一些精华,以支持我的[显然颇有争议的]观点。

Historically, COM placed a giant try/except around your server's methods. If your server encountered what would normally be an unhandled exception, the giant try/except would catch it and turn it into the error RPC_E_SERVERFAULT. It then marked the exception as handled, so that the server remained running, thereby "improving robustness by keeping the server running even when it encountered a problem."

Mind you, this was actually a disservice.

The fact that an unhandled exception occurred means that the server was in an unexpected state. By catching the exception and saying, "Don't worry, it's all good," you end up leaving a corrupted server running.

[ . . . ]

Catching all exceptions and letting the process continue running assumes that a server can recover from an unexpected failure. But this is absurd. You already know that the server is unrecoverably toast: It crashed!

Much better is to let the server crash so that the crash dump can be captured at the point of the failure. Now you have a fighting chance of figuring out what's going on.

您可以 [并且应该] 在他的博客上阅读整篇文章:How to turn off the exception handler that COM "helpfully" wraps around your server .

关于c# - 主要方法代码完全在 try/catch : Is it bad practice? 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4827628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com