what is the best way to handle an exception?
and why should i never write:
catch (Exception ex) { throw ex; }
what is the best way to handle an exception?
and why should i never write:
catch (Exception ex) { throw ex; }
Why would you catch the expection to just throw it again, if you were to catch the exception and do something other than just throw it, it would be fine!
try
{
}
catch(Exception ex)
{
// do something like log the exception
throw ex; // let another catch block handle the expection.
}
The best way to handle an exception is to do something meaningful in the catch
block (the one which in your example contains throw ex
). The definition of "meaningful" completely depends on your needs.
You should not do catch (Exception ex) { throw ex; }
because that brakes the exception chain. It is perfectly fine to catch an exception, handle it and re-throw so that the calling code can see it, but you should be doing so like this:
catch (Exception ex) { /* handling code; */ throw; }
If you're in a position in the code where you can deal with the exceptional case that is described by the exception then you should:
try
{
// code that might throw an exception
}
catch
{
// deal with the exception here, for example ask the user to re-enter
// the input that threw the exception
}
If you're not in a position to handle the exceptional case, there's no point catching the exception - just let it pass up the call stack until the calling code is in a position to handle it.