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

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

问题描述

我看到有人说,这是不好的形式使用捕不带任何参数,尤其是如果赶上没有做任何事情:

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();
}

据我所知,投入清理code之间的唯一区别finally块,并把清理code中的在try..catch块后,如果您在您的try块return语句(以这种情况下,清理code。在最终将运行,但在try..catch后code不会)。

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).

否则,有什么特别之处最后?

Otherwise, what's so special about finally?

推荐答案

最大的区别是,的try ... catch 会吞下例外,隐瞒事实,即发生了错误。 try..finally 将运行清理code,然后异常会继续下去,被一些知道该怎么用它做处理。

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.

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

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