它是不好的做法,从内尝试捕捉finally块返回? [英] Is it bad practice to return from within a try catch finally block?

查看:135
本文介绍了它是不好的做法,从内尝试捕捉finally块返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我碰到一些code今早看起来像这样来了:

So I came across some code this morning that looked like this:

try
{
    x = SomeThingDangerous();
    return x;
}
catch (Exception ex)
{
    throw new DangerousException(ex);
}
finally
{
    CleanUpDangerousStuff();
}

现在这个code编译罚款和作品,因为它应该,但它只是感觉不对一个try块内返回,尤其是如果有一个最终建立关联。

Now this code compiles fine and works as it should, but it just doesn't feel right to return from within a try block, especially if there's an associated finally.

我的主要问题是,如果最终抛出它自己的异常,会发生什么?你已经有了一个返回的变量也是一个异常处理......所以我想知道别人的想法有关从try块内返回?

My main issue is what happens if the finally throws an exception of it's own? You've got a returned variable but also an exception to deal with... so I'm interested to know what others think about returning from within a try block?

推荐答案

没有,这不是一个不好的做法。把收益在有意义提高可读性和可维护性,使您的code容易理解。你不应该关心为最后如果遇到收益语句块将被执行。

No, it's not a bad practice. Putting return where it makes sense improves readability and maintainability and makes your code simpler to understand. You shouldn't care as finally block will get executed if a return statement is encountered.

这篇关于它是不好的做法,从内尝试捕捉finally块返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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