【问题标题】:Return from method, in the "try" block or after "catch" block?从方法返回,在“try”块中还是在“catch”块之后?
【发布时间】:2016-08-26 05:18:48
【问题描述】:

以下两种方法有区别吗?

哪个更好,为什么?

Prg1:

public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }    
}

Prg2:

public static boolean test() throws Exception {
    try {
        doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return true;    
}

【问题讨论】:

  • 我更喜欢第二个 sn-p,因为我觉得它更干净(更清晰)。我认为这不会影响性能。
  • 我更喜欢第一个,因为如果你决定在本地处理异常而不是重新抛出它会发生什么。

标签: java exception try-catch


【解决方案1】:

我假设这是一个普遍的问题。否则我可能会评论您方法的其他方面。

我认为在这种情况下或像这样的小方法并不重要。该方法足够简短,可以立即了解发生了什么,与什么相关等。

但是,对于较长的方法,第一个示例中的流程更容易遵循。 在我看来。它将相关的代码和相关的场景放在一起。在阅读方法时,catch 块不会破坏正常的执行流程,使其更加明显和“流畅”。

public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }    
}

但我不会对所有方法一概而论;一切都与上下文有关。

【讨论】:

    【解决方案2】:

    考虑这些不返回常量表达式的情况:

    案例一:

    public static Val test() throws Exception {
        try {
            return doSomething();
        } catch (Exception e) {
            throw new Exception("No!");
        }
        // Unreachable code goes here
    }
    

    案例 2:

    public static Val test() throws Exception {
        Val toReturn = null;
        try {             
            toReturn = doSomething();
        } catch (Exception e) {
            throw new Exception("No!");
        }
        return toReturn;
    }
    

    我更喜欢第一个。第二个更冗长,在调试时可能会引起一些混乱。

    如果test() 错误地返回null,并且您看到toReturn 被初始化为null,您可能会认为问题出在test() 上(尤其是当test() 不仅仅是这样的简单示例时)。

    即使它只能在 doSomething 返回 null 时返回 null。但这可能一目了然。


    然后您可以争辩说,为了保持一致性,最好始终使用第一种形式。

    【讨论】:

      【解决方案3】:

      没有区别,但是第一个Prg1比Prg2快。

      【讨论】:

      • 有什么证据吗?
      • 通过使用这个代码你可以证明它:long startTime,endTime,duration;开始时间 = System.nanoTime();测试2(); // 或 test1() endTime = System.nanoTime();
      • 首先你要改变程序。
      • 通过在代码中添加指标,实际上会影响代码的功能。您的程序现在必须运行它不应该运行的步骤。这可能会改变编译器生成 IL 的方式
      【解决方案4】:

      不,这两种方法之间没有区别。 通过在处理异常后立即恢复程序流程,它将在这两种情况下有效地返回真值。 只有发生异常时才会访问catch。

      【讨论】:

        猜你喜欢
        • 2016-05-06
        • 2012-05-18
        • 2016-01-15
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 2014-07-16
        • 2017-07-20
        • 1970-01-01
        相关资源
        最近更新 更多