开发者

Exception catching

What is the difference between

 try
 {
     ... 
 }
 catch (NHibernate.ADOException开发者_如何转开发 exception)
 {}

and

try
{
    ... 
}
catch (exception ex)
{}


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜