I have searched for an answer to my question but not been able to find one. Apologies if the answer is there and I am duplicating!
I keep seeing try/catch code such as.....
try
{
//Do whatever
}
catch (Exception ex)
{
MessageBox.Show("Oops, something went wrong!");
}
Which will result in a warning ex is never used.
So my question is... Although ex is never used is there any benefit in the declaration? I was told that maybe it adds detail to the stack trace? Sometimes I see catch(Exception) which stops the warning but what benefits does this bring, if any? If I was to write this and not use the exception in any way I wouldn't declare ex...
try
{
//Do whatever
}
catch
{
MessageBox.Show("Oops, something went wrong!");
}
Not a big problem but it would be good to know for sure!
Thanks
Fred
You can use the following pattern, still declaring the specific exception type, without a variable, to ensure Structured Exception Handling (SEH) is still happening:
try
{
//Do whatever
}
catch (IOException)
{
MessageBox.Show("Oops, something went wrong in the IO!");
}
catch (Exception)
{
MessageBox.Show("Oops, something went wrong!");
}
This is not a practice I would normally use, as I would probably log the exception details if not rethrowing it.
It's important to note that there's a difference in your two posted code blocks. catch (Exception ex)
will only catch CLR-defined exceptions (those that derive from Exception
). catch
alone will catch anything - including unmanaged exceptions that the CLR hasn't caught or wrapped itself.
If you want to avoid your compiler warning without changing the behaviour of the code, or if you want to avoid the warning whilst still catching a specific exception type, you can use this instead:
catch (Exception)
{
}
The benefit here is that you can be specific: catch (SqlException)
, for example. If you're not using the variable then declaring give the warning, but the type-specific behaviour is still useful.
Regardless, declaring the exception doesn't add anything to the information (stack trace or otherwise), unless you wrap-and/or-rethrow the exception explicitly. (Incidentally, don't use throw ex
to rethrow, because this does lose information: just use throw
.)
Suppressing exceptions is usually bad form...let them travel up the stack.
Regarding "adds detail", rethrow the exception using throw
to preserve the stack trace otherwise you will lose detail. Again, the alternative is there to not catch it at all. If you don't have any use for the exception (recovery, unwind, etc.), chances are there isn't a good reason to catch it.
See: What is the proper way to re-throw an exception in C#?
See also: "Back to Basics - Exceptions"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With