Catch(Exception)
和 Catch(Exception ex)
有什么区别。我可以看到两者都给我预期的输出。那么实际的区别是什么?推荐哪一个?
假设代码如下。
int a = 1, b = 0;
try
{
int c = a / b;
Console.WriteLine(c);
}
建议使用以下哪个 catch block ?它们之间的实际区别是什么?
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
或
catch (Exception)
{
Console.WriteLine("Oh NO!!");
}
最佳答案
嗯,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 的绿色烟雾) happend 只是打印出“哦不”并继续“?具有 Exception 类的模式 是这样的:
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
}
关于c# - Catch(Exception) 和 Catch(Exception ex) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173222/