What if I had something like this:
try
{
//work
}
catch (ArgumentNullException e)
{
HandleNullException();
Logger.log("ArgumentNullException " + e);
DoSomething();
}
catch (SomeOtherException e)
{
HandleSomeOtherException();
Logger.log("SomeOtherException " + e);
DoSomething();
}
catch (Exception e)
{
HandleException();
Logger.log("Exception " + e);
DoSomething();
}
Now as we can see, I’m trying to handle exceptions for some different cases. BUT whenever an exception is raised, I’m always calling the method DoSomething() at the end. Is there a smarter way to call DoSomething() if there is an exception? If I added a finally block and called DoSomething() there, it would always be called, even when there is no exception. Any suggestions?
What you are looking for is known in the CLI standard (partition IIA, chapter 18) as a fault handler. Although .NET implements them, the C# language does not directly support them. However, they can be emulated:
Note that there is no need to set the flag inside every
catchhandler, as some answers here suggest. Simply negate the test, and you only need to set the flag once, at the end of thetryblock.