c# - Catch(Exception) 和 Catch(Exception ex) 的区别

标签 c# .net exception try-catch

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/

相关文章:

c# - 可点击的 GridViewRow 覆盖子超链接

c# - 允许用户在文本框中插入 TAB,但不能插入换行符

android - 如何检查 Android 中的异常对象类型?

C# 和.NET : stackalloc

c# - 太多的扩展方法会降低性能吗?怎么运行的

c# - 返回只读并发列表

.net - 从客户端检查 RabbitMQ 队列大小

java - 这在堆栈跟踪中意味着什么?

java - 修复错误 : Unreported Exception InterruptedException

c# - 网络核心 : how to make the browser show file as being downloaded before it's sent