Is this a bad practice to catch a non-specific exception such as System.Exception? Why?
.net, c#, exception
Solution
The mantra is:
- You should only catch exceptions if you can properly handle them
Thus:
- You should not catch general exceptions.
In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could `throw` after you log them).
Your coder is using `throw` (not `throw ex`) which is good.
This is how you can catch multiple, specific exceptions:
try
{
// Call to a WebService
}
catch (SoapException ex)
{
// Log Error and eat it
}
catch (HttpException ex)
{
// Log Error and eat it
}
catch (WebException ex)
{
// Log Error and eat it
}
This is pretty much equivalent to what your code does. Your dev probably did it that way to avoid duplicating the "log error and eat it" blocks.
Problem
I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)? - Catch a generic exception (Exception ex) - The use of "if (ex is something)" instead of having another catch block - We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do. Code: ``` try { // Call to a WebService } catch (Exception ex) { if (ex is SoapException || ex is HttpException || ex is WebException) { // Log Error and eat it. } else { throw; } } ```