C# (not ASP/MVC/WinForms) - Catch all exceptions in a class

后端 未结 3 1459
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 03:31

Some background info

I am programming in a system that uses a proprietary programming language, with the option of using specially attributed .Net classes in the propri

3条回答
  •  Happy的楠姐
    2021-02-07 04:03

    As I understood the answer, you need to catch and rethrow unhandled exception, right? You can add handler for the AppDomain.UnhandledException Event:

      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
    
      static void MyHandler(object sender, UnhandledExceptionEventArgs args)
      {
            Exception e = (Exception) args.ExceptionObject;
            // handle exception here, you can easily package exceptions there.
      }
    

    Update:

    I've discovered another event in AppDomain class, AppDomain.FirstChanceException Event:

    Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

    May be this can solve your problem - this event occurs before any code in catch blocks.

提交回复
热议问题