c#中的全局异常处理(控制台应用程序)

c#中的全局异常处理(控制台应用程序)

问题描述:


可能重复:

。NET控制台应用程序中的全局异常处理程序

我已经阅读了很多关于*上的全局异常处理的东西,但是我找不到任何指向我的主题的东西。我写了一个控制台应用程序,捕获异常只是在他们发生的方法。没有投掷。我想要的是一个全局异常处理。我没有关于异常处理的基本指导,但是除了这些基础知识以外,还没有任何想法。应该有一个处理这些异常的类(由不同类的方法抛出)。我不需要任何错误记录或错误报告机制。只需要基础(模式无论...)来实现这种全局处理。感谢您阅读到目前为止!

I've read a lot of things about global exception handling on *, but I could not find anything refering to my topic properly. I wrote a console application that catches exceptions just in the methods they occur. No throw's at all. What I want to have is a global exception handling. I no the basic guidlines about exception handling, but got no idea beyond those basics. Imaginary there should be one class handling those exceptions (thrown by the methods from the different classes). I don't need any error-recording or error-reporting mechanisms yet. Just need the basics (patterns whatever...) to implement this global handling. Thanks for reading so far!

全局处理异常仅适用于某些任务,例如记录错误或优雅退出应用程序。

Handling exceptions globally is good for certain tasks only, such as logging errors or graceful exit of the application.

在所有其他情况下,建议您在最相关的位置处理异常。例如,如果您从应用程序进行Web服务调用,并且如果该服务不可用,那么应该处理您进行Web服务调用的异常,而不是在全局捕获。这提高了代码的可读性,并且在全局级别做任何明智的操作并不实用,因为您几乎没有关于异常发生位置的信息。 (当然你有堆栈跟踪,但是它不可用于编程操作)

In all other cases, it is recommended that you handle the exception in the most relevant place. For example, if you make a web service call from your app and if the service is not available, you should handle that exception where you make the webservice call instead of catching it globally. This improves the readability of the code, and also it's not practical to do anything sensible at global level as you have very little information on where the exception originated. (Of course you have the stack trace, but its not readily available for programmatic manipulation)

但是,您可以通过将处理程序附加到 AppDomain.UnhandledException 也在@Jesse的评论中指出

However, you can add an application wide exception handler by attaching a handler to AppDomain.UnhandledException as also indicated in the comment by @Jesse