好吧,这与只有一个区别catch(Exception ex)
相同:我们可以访问异常类(错误原因)实例。通常你需要一个异常类实例来打印出原始消息:catch(Exception)
catch(Exception ex)
try {
...
}
catch (AppServerException e) {
Console.WriteLine("Application server failed to get data with the message:");
Console.WriteLine(e.Message); // <- What's actually got wrong with it
}
如果您不需要异常类实例,例如您打算只使用异常,则 catch(Exception ex) 语法过多,catch(Exception) 是可取的:
try {
c = a / b;
}
catch (DivideByZeroException) {
c = Int.MaxValue; // <- in case b = 0, let c be the maximum possible int
}
最后。不要在不重新处理的情况下捕获一般异常类:
try {
int c = a / b;
}
catch (Exception) { // <- Never ever do this!
Console.WriteLine("Oh NO!!");
}
你真的想编写“任何错误(包括来自 CPU 的绿色烟雾)发生的代码,只需打印出“哦,不”并继续”吗?带有异常类的模式是这样的:
tran.Start();
try {
...
tran.Commit();
}
catch (Exception) {
// Whatever had happened, let's first rollback the database transaction
tran.Rollback();
Console.WriteLine("Oh NO!");
throw; // <- re-throw the exception
}