Ceshion Ceshion - 20 days ago 8
C# Question

Which is better to catch all exceptions except given types: catch and rethrow or catch when?

If I wanted to catch all exceptions except for given types, and those specific types would be re-thrown to be caught in a higher context, would it be better to do:

try
{
//Code that might throw an exception
}
//Catch exceptions to be handled in this context
catch (Exception ex) when (!IsExcludedException(ex))
{
//Handle leftover exceptions
}


Or would it be better to do:

try
{
//Code that might throw an exception
}
catch (SpecificException)
{
throw;
}
//Catch exceptions to be handled in this context
catch (Exception ex)
{
//Handle leftover exceptions
}


Or does it not really matter? Is there a better way?

Answer

The second way is definitely cleaner to analyse and it's what I see the most. The specific catch happens first and doesn't trigger the generic one, but you still have a fallback if you didn't implement a specific one. Also, for handling more than one specific exception you'd need more !(ex is SpecificException) checks as well.