吞咽异常渔获抛出/ finally块 [英] Swallowing exception thrown in catch/finally block

查看:139
本文介绍了吞咽异常渔获抛出/ finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我碰到过,我不得不吞下被清理代码在捕获抛出的异常的情况下 / 最后块,以防止原始异常被吞噬

Usually I come across situations where I have to swallow an exception thrown by the clean up code in the catch/finally block to prevent the original exception being swallowed.

例如:

// Closing a file in Java
public void example1() throws IOException {
    boolean exceptionThrown = false;
    FileWriter out = new FileWriter("test.txt");
    try {
        out.write("example");
    } catch (IOException ex) {
        exceptionThrown = true;
        throw ex;
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            if (!exceptionThrown) throw ex;
            // Else, swallow the exception thrown by the close() method
            // to prevent the original being swallowed.
        }
    }
}

// Rolling back a transaction in .Net
public void example2() {
    using (SqlConnection connection = new SqlConnection(this.connectionString)) {
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction = command.BeginTransaction();
        try {
            // Execute some database statements.
            transaction.Commit();
        } catch {
            try {
                transaction.Rollback();
            } catch {
                // Swallow the exception thrown by the Rollback() method
                // to prevent the original being swallowed.
            }
            throw;
        }
    }
}

让我们假定记录任何的例外是不是在方法块范围的选项,但会通过代码调用例1()例2()方法。

Let's assumed that logging any of the exceptions is not an option in the scope of method block, but will be done by the code calling the example1() and example2() methods.

时吞咽通过的close()回滚()方法是个好主意?如果没有,什么是处理上述情况,这样的异常没有被吞了更好的办法?

Is swallowing the exceptions thrown by close() and Rollback() methods a good idea? If not, what is a better way of handling the above situations so that the exceptions are not swallowed?

推荐答案

我不。风扇捕获并重新抛出异常

I'm not a fan of catching and rethrowing an exception.

如果你抓住它,做的的东西的它 - 即使它只是记录例外。

If you catch it, do something with it - even if it's just logging the exception.

如果你不能用它做任何事情,不要抓住它 - 增加一个throws子句的方法签名

If you can't do anything with it, don't catch it - add a throws clause to the method signature.

捕获异常告诉我,要么你可以处理一个特殊的情况,有一个恢复计划或责任止于此,因为异常不能在窗体中的任何进一步传播(如无堆栈跟踪回用户)。

Catching an exception tells me that either you can deal with an exceptional situation and have a recovery plan or "the buck stops here" because an exception cannot propagate in that form any farther (e.g., no stack traces back to the user).

这篇关于吞咽异常渔获抛出/ finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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