Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching exceptions C#

Tags:

c#

exception

What is right way to do.

To catch exceptions from most specific to most general or opposite.

if I write

try
{
...
}
catch( Exception e )
{
...
}
catch( NullReferenceException nre )
{
...
}

Will NullReferenceException nre ever be caught?

like image 458
eomeroff Avatar asked Dec 01 '22 09:12

eomeroff


2 Answers

try
{
...
}
catch( NullReferenceException nre )
{
...
}
catch( Exception e )
{
...
}

Also I wouldn't be catching NullReferenceException, I would test if the value I am trying to access is not null before actually accessing it or use the null coalescing operator (??) to make sure this exception never happens.

Catching a general Exception should be avoided. IMHO you should do this only in some global exception handler because you can rarely handle the case of all possible exceptions every time you call a method. In this case you should only catch some specific exceptions if any and take proper actions.

like image 57
Darin Dimitrov Avatar answered Dec 04 '22 12:12

Darin Dimitrov


No, you have to go from the most specific to the most general. Your example has to look like

try
{

}
catch(NullReferenceException nre)
{

}
catch(Exception e)
{

}

see here (MSDN)

like image 35
sloth Avatar answered Dec 04 '22 11:12

sloth