为什么 try {...} finally {...} 好;尝试 {...} catch{} 不好? [英] Why is try {...} finally {...} good; try {...} catch{} bad?

查看:31
本文介绍了为什么 try {...} finally {...} 好;尝试 {...} catch{} 不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到有人说使用不带参数的 catch 是不好的形式,尤其是当 catch 没有做任何事情时:

I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:

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

但是,这被认为是好的形式:

However, this is considered good form:

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

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

As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).

否则,finally 有什么特别之处?

Otherwise, what's so special about finally?

推荐答案

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

The big difference is that try...catch will swallow the exception, hiding the fact that an error occurred. try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.

这篇关于为什么 try {...} finally {...} 好;尝试 {...} catch{} 不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆