1
votes

I want to catch all exceptions raised (handled or unhandled) to log them. for unhandled i use ThreadExceptionEventHandler and UnhandledExceptionEventHandler but i want to catch and exceptions that are in try catch block with or without (Exception e). It's possible to inherit the exceptions class to create a general event?

6

6 Answers

2
votes

Starting from Windows XP you can get notified about every raised exception, even before it's known to be handled or not. This is available via so-called "vectored" exception handling, which is actually a little addition to the standard structured exception handling.

Call AddVectoredExceptionHandler to add your own handler. You'll get called right after the exception is raised, either by explicit throw/__CxxThrowException/RaiseException or implicitly by the processor (access violation or etc.)

You can log the exception in your handler (produce stack dump for instance), and return EXCEPTION_CONTINUE_SEARCH.

1
votes

Inheriting from Exception to provide your own Exception class would work fine for exceptions you generate in your code, and you could use the inner exception constructor to carry built in exceptions up the chain.

If you were goig to try that, you'd need to replace all of your exception handling code, and probably add a chunk more as well. I don't think it'd be substantially better than Peter McG's approach, but it might allow you different options when preserving & examining the original exceptions and re-throwing, for example keeping a record of whether it has already been logged lower down the chain.

Just to be explicit, it is possible to use:

catch (Exception e)
{
   log(e);
   throw;
}

which will rethrow the original exception.

1
votes

Sounds like you've got the Unhandled Exceptions as covered as possible, for handled exceptions can't you just eventually...

catch (Exception e) {}

and call the same logging function with the instance.

If not and you really must have some instances where you have a catch but without catching an instance you can use...

catch { throw; }

to re-throw the exception to be eventually caught and logged as an un-handled exception.

1
votes

C++ allows for catch(...) which catches all exceptions but doesn't really allow to analyze them in depth. (see using catch(...) (ellipsis) for post-mortem analysis ) I'm not sure if it will work in C# though.

0
votes

No, thats not possible.

The only way this would be possible is using the debugging APIs (the managed version is named mdbg)

0
votes

There's no way to catch an already caught exception except, may be, working with AddVectoredExceptionHandler.

Having said that, you can use a catch-and-rethrow approach:

catch(Exception e) {
   Logger.Log(e);
   throw;
}

or

catch(Exception e) {
   bool rethrow = LoggerStrategy.Log(e);
   if(rethrow) { throw; }
}

Better still, use the Logging Application Block.