views:

54

answers:

3
+1  Q: 

Exception catching

What is the difference between

 try
 {
     ... 
 }
 catch (NHibernate.ADOException exception)
 {}

and

try
{
    ... 
}
catch (exception ex)
{}
+6  A: 

In the catch block you specify which exceptions you wish to catch. So if you have

try {}
catch(Exception e){}

it will catch all exceptions that derive from the Exception class (so ALL exceptions). If you have:

try{}
catch (NHibernate.ADOException exception){}

it will only catch exceptions that are or derive from ADOException. So if you get an ArgumentException, it will pass through as if there were no try/catch.

Grzenio
Also If you are expecting specified exception it is a good practis to catch it's actuall type then `Exception` type. In this case it's nicer solution to use `NHibernate.ADOException`
ŁukaszW.pl
+1  A: 

I'm assuming you meant

catch (Exception ex) {}

with the second snippet.

Then the difference is that the first one will only catch one specific type of exception, namely NHibernate.ADOException while the second one will enter the catch block for all exceptions that could possibly be thrown.

The second is usually bad practice since you're claiming to handle every conceivable type of error. However, it can make sense in the outermost scope as a catch-all for any exception that got through.

Joey
A: 

Using catch { Exception } is strongly not recommended, because this actually hides a bugs. In every place where exception may be thrown, it is necessary to catch only expected exception types, even if this requires to write more code lines. When unexpected exception is thrown, program must crash, this is the only way to fix the bug.

Alex Farber