Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't declare unused exception variable when using catch-all pattern

Tags:

c#

try-catch

what is a best practice in cases such as this one:

try
{
   // do something
}
catch (SpecificException ex)
{
    Response.Redirect("~/InformUserAboutAn/InternalException/");
}

the warning i get is that ex is never used.

however all i need here is to inform the user, so i don't have a need for it.

do i just do:

try
{
   // do something
}
catch
{
    Response.Redirect("~/InformUserAboutAn/InternalException/");
}

somehow i don't like that, seems strange!!? any tips? best practices?

what would be the way to handle this.

thnx

like image 336
b0x0rz Avatar asked Jan 23 '26 04:01

b0x0rz


2 Answers

You just don't declare the variable:

try
{
   // do something
}
catch (SpecificException)
{
    Response.Redirect("~/InformUserAboutAn/InternalException/");
}

This is a moot point when catching System.Exception (in your original example, which is not exactly the same as an empty catch -- an empty catch will also catch COM exceptions, for instance), but this is the correct construct to use.

If you run your code through other analysis engines (Gendarme, for instance), you will also be warned that catching a plain Exception is poor practice because it can mask other exceptions besides what you really wanted to catch. That's bitten me a few times while maintaining legacy code -- we were catching and ignoring an Exception on a file delete (or something like that), but the main logic wasn't working correctly. We should have been only catching an IOException, but we were catching and discarding the NullReferenceException that was causing the failure.

That's not to say you never should catch Exception; just rarely.

like image 114
Mark Rushakoff Avatar answered Jan 24 '26 20:01

Mark Rushakoff


If you don't need Exception's variable to get some information from it, don't declare it

try { }
catch ( ) 

is equal to

try { }
catch (Exception) { }

Use this

try { }
catch (Exception ex) { var m = ex.Message; }

if you need some information to gather.

Use this

try { }
catch (FooException) { }
catch (BarException) { }

if you need to catch only specific types of exceptions, i.e. SomeAnotherException will not be caught.

like image 20
abatishchev Avatar answered Jan 24 '26 18:01

abatishchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!