c# - 为什么 try {...} finally {...} 好;试试 {...} catch{} 不好?

标签 c# .net exception-handling try-catch try-catch-finally

我看到有人说使用不带参数的 catch 是一种不好的形式,尤其是当 catch 什么都不做的时候:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
catch   // No args, so it will catch any exception
{}
reader.Close();

然而,这被认为是好的形式:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
finally   // Will execute despite any exception
{
  reader.Close();
}

据我所知,将清理代码放在 finally block 中和将清理代码放在 try..catch block 之后的唯一区别是你的 try block 中是否有 return 语句(在这种情况下,清理代码in finally 会运行,但 try..catch 之后的代码不会)。

否则,finally有什么特别的?

最佳答案

最大的区别是 try...catch 会吞下异常,隐藏错误发生的事实。 try..finally 将运行您的清理代码,然后异常将继续运行,由知道如何处理它的东西处理。

关于c# - 为什么 try {...} finally {...} 好;试试 {...} catch{} 不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/128818/

相关文章:

Java:如何编写 try-catch-repeat block ?

design-patterns - 里氏替换原则 (LSP)、代理模式和异常(exception)

c# - 是否可以在 C# 中使用无类型泛型列表?

c# - 不使用空合并运算符进行延迟初始化有什么好的理由吗?

c# - 设置默认 "ok"和 "cancel"按钮

c# - 哪个更流畅 - 更长或更短的语法?

c# - 如何向我的 backgroundworker dowork 事件添加耗时的进度?

c# - 在csproj文件中配置XamlRuntime和DefaultXamlRuntime意义

.net - 如何结束excel.exe进程?

.net - 为什么 XmlDocument.LoadXml 抛出 System.Net.WebException?