Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch and Catch(Exception e) in C#

Tags:

c#

.net

I guess there is no difference between these three parts of code, is not it?

   try
    {
       // .............
    }
    catch
    {
        // ............. 
    }

and

   try
    {
       // .............
    }
    catch(Exception)
    {
       // .............  
    }

and

try
{
   // .............
}
catch(Exception e)
{
    // ............. 
}

However I am almost savvy when should be used the first one and when - the second. But I would like you to tell your ideas.

like image 471
Alexandre Avatar asked Jan 30 '26 09:01

Alexandre


2 Answers

The first one will also catch thrown objects that aren't exceptions.
(this can happen from non-CLS-compliant code)

The second one will not give a compiler warning if you don't actually use the exception variable.

The third one should be used only if you actually need to inspect the thrown exception (eg, to log it).

like image 125
SLaks Avatar answered Feb 01 '26 21:02

SLaks


Those bits of code are quite a bit different.

The first does not allow you to take any information from the exception that occurred. It will catch anything, but you won't have any clue what was caught.

The second does not allow you to do anything, but at least lets you specify what kind of exception. In your example, since you have indicated Exception, it will catch everything that derives from Exception. But it could be altered to fine-tune what is caught - but still permit you to do nothing with it.

the third lets you actually access the exception and get info from it.

like image 25
Andrew Barber Avatar answered Feb 01 '26 23:02

Andrew Barber



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!