捕获所有异常

时间:2013-03-05 23:14:20

标签: c# wcf exception-handling

我有一个项目可能会在任何函数和对象上抛出异常,有没有办法在整个框架/程序中捕获任何和所有异常,以便我可以记录它们以便以后可以看到它们?我想要调用堆栈和异常消息。我不一定知道异常将在哪里抛出,但我想记录在程序的整个生命周期中发生的任何异常。反正有没有这样做?我不想尝试并捕获任何可能的异常抛出功能。由于未处理的异常,程序将中断,但我想先记录它。

6 个答案:

答案 0 :(得分:3)

是的,有办法做到这一点。 在主要部分写下以下行:

// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(MainForm_UIThreadException);

// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event. 
AppDomain.CurrentDomain.UnhandledException +=
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

并处理异常

private static void MainForm_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
    //do something
}

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    //do something
}

答案 1 :(得分:1)

捕获异常的一个要点是根据抛出的异常类型正确处理它们。通过拥有一个大的异常处理程序,您无法处理个别异常,而可能只是吞下它们。但这并不是说在所有情况下都无法完成或不应该这样做。

如果您的项目需要一个大型处理程序,那么您可以简单地处理AppDomain.UnhandledException事件。即使您在其他地方捕获异常,处理此方法也是一个好主意,以确保您的程序不会在错过异常时抛出不友好的错误。这假设您正在创建WinForm

由于您还使用WCF,因此您可以查看IErrorHandler接口以帮助处理故障消息。

答案 2 :(得分:1)

  

有没有办法在整个框架/程序中捕获任何和所有异常,以便我可以记录它们以便以后可以看到它们?

捕获 所有 应用程序类型的所有未处理异常的唯一方法是使用已经提到的AppDomain.CurrentDomain.UnhandledException。但是,你不能阻止你的应用程序终止使用该事件(嗯,你可以,但我不会告诉你如何,因为它是一种hackish)。

然而,在大多数框架中,有一些方法可以捕获未处理的异常,这些异常允许您只是接受异常并继续前进。由于您提到了WCF,因此您可能希望阅读IErrorHandler

  

我不想尝试并捕获任何可能的异常抛出函数。

我就是这样做的。 Do NOT catch that exception。 ;)

答案 3 :(得分:0)

您可以在应用域级别捕获例外 - App Domain Exception

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

如果您阅读该链接,则会提到某些其他事件可能导致应用域无法触发 - 例如ThreadException - 因此可能需要多个处理程序。

Application.ThreadException += new ThreadExceptionEventHandler (ThreadExceptionHandler);

并注意以下内容:(与winforms有关 - SetUnhandledExceptionMode

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

答案 4 :(得分:0)

您可以随时使用AppDomain.UnhandledException

static void Main()
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
}

private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
    Logger.Log((Exception)args.ExceptionObject);
}

答案 5 :(得分:0)

  

有没有办法捕捉整个过程中的任何和所有异常   框架/程序,以便我可以记录它们,以便我以后可以看到它们?

,桌面应用程序或Web应用程序的处理程序可以处理未处理的异常。在桌面应用程序中,该事件称为UnhandledException。在Web应用程序中,它是应用程序入口点上的Application_Error(通常是Global.asax.cs)。

  

我不想尝试并抓住任何可能的异常抛出   功能。程序将因未处理的异常而中断,但我   想先登录。

如果您不想捕获异常,则可以随时重新抛出。它会继续冒泡而导致程序崩溃。

catch(Exception ex)
{
    //logging here
    throw;//rethrow
}
  

我想要调用堆栈和异常消息。

Exception类包含这些。对于事件处理程序,有多种方法可以访问,具体取决于它的应用程序类型。

相关问题