简体   繁体   English

使用两次试捕?

[英]Use of having two try-catch?

What is the benefit of having two try-catch as seen below? 如下所示,进行两次try-catch有什么好处? Taken from the book Beginning Hibernate. 摘自《冬眠开始》一书。

protected void rollback() {
        try {
            getSession().getTransaction().rollback();
        } catch (HibernateException e) {
            // TODO change to log
            System.out.println(e);
        }

        try {
            getSession().close();
        } catch (HibernateException e) {
            // TODO change to log
            System.out.println(e);
        }
    }

它保证即使rollback()抛出异常,也将调用close()

The initial purpose was to close the session even if the rollback() method throws an exception but this solutions is not good enough. 最初的目的是即使rollback()方法引发异常也要关闭会话,但是这种解决方案还不够好。

If roolback throws a RuntimeException the close code will never be called 如果roolback抛出RuntimeException,则永远不会调用关闭代码

You should do the following: 您应该执行以下操作:

protected void rollback() {
        try {
            getSession().getTransaction().rollback();
        } catch (HibernateException e) {
            // TODO change to log
            System.out.println(e);
        } finally {
            try {
                getSession().close();
            } catch (HibernateException e) {
                // TODO change to log
                System.out.println(e);
            }
        }
    }

This ensures that the close code will be called no matter what. 这样可以确保无论如何都将调用关闭代码。

None, really. 没有,真的。 If you replace that code with 如果您将代码替换为

protected void rollback() {
        try {
            getSession().getTransaction().rollback();
            getSession().close();
        } catch (HibernateException e) {
            // TODO change to log
            System.out.println(e);
        }
    }

you still get pretty much the same info. 您仍然可以获得几乎相同的信息。 There are some minute differences: 有一些细微的差异:

in the first case, the line getSession().close(); 在第一种情况下,行getSession().close(); will still be called even if getSession().getTransaction().rollback(); 即使getSession().getTransaction().rollback();仍将被调用 throws an exception, while in my example it will not. 引发异常,而在我的示例中则不会。 The proper way to handle this however is to use a finally block if you want that .close() line to be called no matter what. 但是,处理此问题的正确方法是如果无论如何都希望调用.close()行,请使用finally块。

The reason is independence between these parts. 原因是这些部分之间的独立性。 Both parts may fail independently. 这两个部分可能会独立失败。 (And handled independently as well). (并独立处理)。 A fail of 'rollback' invocation won't prevent execution of 'close' statement, as opposite to a single try-catch block approach for this case. 与这种情况下的单个try-catch块方法相反,失败的“回滚”调用不会阻止执行“ close”语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM