代码之家  ›  专栏  ›  技术社区  ›  ARX

Java编译器说“缺少返回语句”,即使它是不可访问的

  •  0
  • ARX  · 技术社区  · 5 年前

    我在Java 15上有这个方法:

    int myMethod() throws MyException {
        try {   
            // do something
            return someInt;
        } catch (SQLException e) {
            throwingMethod(e);
        }
    }
    

    throwingMethod() SQLException 变成一个 MyException 然后扔掉后者。因为catch子句总是抛出 原始的异常 ,保证控制永远不会到达catch子句的末尾。

    return 0; 调用throwingMethod()只是为了让编译器高兴(我知道是这样的)?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Andy Turner    5 年前

    然后扔掉后者

    如果要指示执行不会超出该行,请将方法声明为returning MyException ,和 throw 调用它的结果:

    MyException throwingMethod(SQLException e) throws MyException {
       // Either return or throw MyException.
       // Throwing is better if you need to guarantee it will actually be thrown,
       // and can't rely on it being thrown at the call site.
    }
    
    // In the catch:
    throw throwingMethod(e);
    

    (*)如果你想知道为什么根据规范,你可以在 JLS 8.4.7 :

    你的方法有一个返回类型( int ),因此它不能正常完成(例如没有异常或返回)。

    但是在 JLS 14.22

    • 如果表达式语句是可到达的,则它可以正常完成。

    ; 是表达式语句),则认为它可以正常完成。

    然而:

    • break、continue、return、throw或yield语句不能正常完成。

    使之不能正常完成。我想你可以用 return 相反;但是