SKJ*_*SKJ 8 .net c# exception try-catch
Catch(Exception)和之间有什么区别Catch(Exception ex).我可以看到两个给我预期的输出.那么实际的区别是什么?推荐哪一个?
假设代码在下面.
int a = 1, b = 0;
try
{
int c = a / b;
Console.WriteLine(c);
}
Run Code Online (Sandbox Code Playgroud)
建议使用以下哪个catch块?这些之间的实际区别是什么?
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
要么
catch (Exception)
{
Console.WriteLine("Oh NO!!");
}
Run Code Online (Sandbox Code Playgroud)
好吧,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
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要异常类实例,例如您打算只使用异常,则 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
}
Run Code Online (Sandbox Code Playgroud)
最后。不要在不重新通过的情况下捕获一般 Exception 类:
try {
int c = a / b;
}
catch (Exception) { // <- Never ever do this!
Console.WriteLine("Oh NO!!");
}
Run Code Online (Sandbox Code Playgroud)
你真的想编码“无论发生什么错误(包括 CPU 产生的绿色烟雾),只要打印出“哦不”并继续“?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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11760 次 |
| 最近记录: |