Alex Rivera | Logout

Simple try/catch not making any use of the exception

Asked 2012-08-15T09:45:49.117
11

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

Edit
Report

4 Answers

3

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"

answered 2012-08-15T09:49:28.293
1

If you really don't want to do anything with exception, you can also do like so to avoid the compiler warning:

catch (Exception)
{
  // Stick our head in the sand
}

(or just catch)

answered 2012-08-15T09:49:52.113
1

It's all about the developer and his ability to implement proper logging/debugging in a later term...

this:

catch (Exception ex)
{
    MessageBox.Show("Oops, something went wrong!");
}

could easily be converted to

catch (Exception ex)
{
    Log.Append(ex);
    MessageBox.Show("Oops, something went wrong. Please check the Log file.");
}

sometimes it's merely there for debugging when you run line by line and you can have a break point on the MessageBox.Show line and read the ex variable.

It has it's usefulness, but, at compiled time, if you don't use it, you will get a warning that the variable ex is declared and not used, so, you can track all those and wither Log it, or remove it.

Again, it's all about the programmer choice, and... an unused variable is not that problematic on a ending program.

answered 2012-08-15T09:51:57.387
0

No, there's no point in declaring it unless you actually use it.

answered 2012-08-15T09:47:38.993

Your Answer