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?
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?
Most specific first
Will NullReferenceException nre ever be caught?
true
no, it won't be caught
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)
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.
No it won't.
It goes in the order you place it. Put the most specific exceptions at the top and the general at the bottom.
In order to be caught, the NullReferenceException
shall be the first into the catch-list.
try {
...
} catch (NullReferenceException ex) {
....
} catch (Exception ex) {
...
}
This specifies that you wish to handle the NullReferenceException
in a particular way, that you have something specific to do with. Then, letting the other types of exceptions fall through the most generic catch. On the other hand, non-specific exception handling should be avoided as this MSDN article suggests: Exception Handling
.
Besides, it is better to verify whether the object to be accessed is null (Nothing in Visual Basic) before trying to access it, instead of letting the code access the object and throw this exception when it is null. Here's a useful link for this matter: Exception Handling Best Practices in .NET
.
of course its from most specific to general.
try {
...
} catch (IOException ex) {
....
} catch (Exception ex) {
...
}