有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

需要java Unreachable语句解释

我正在准备OCA Java考试,但我答错了这个问题。我不明白为什么return语句无法访问。我的想法是,即使抛出异常,它也会被捕获,finally块中的语句会被执行,然后return语句会被执行,还是在抛出异常时线程不会执行return语句?更一般地说,有人能解释一下在触发异常的情况下会发生什么,以及在哪些情况下,finally块之后的语句会被执行或不执行。对于一些问题,我得到了正确的答案,而对于其他问题,我没有得到正确的答案,所以我不清楚这里的确切编译器规则

public float parseFloat(String s){
   float f = 0.0f;
   try{
      f = Float.valueOf(s).floatValue();
      return f ;
   }
   catch(NumberFormatException nfe){
      System.out.println("Invalid input " + s);
      f = Float.NaN ;
      return f;
   }
   finally { System.out.println("finally");  }
   return f ;
}

共 (2) 个答案

  1. # 1 楼答案

    1. 如果发生异常,代码将立即退出
    2. 然后它会检查是否有匹配的catch语句,如果有,它的代码就会运行
    3. 无论trycatch块内部发生了什么,finally部分都将始终运行
    4. 如果catch块本身没有返回或抛出异常,try/catch/finally之后的代码将继续运行
    5. 这在代码中是不可能的,因为在成功的情况下,try块会返回,而在失败的情况下,catch块会返回

    因此,可能有一种理论上的情况,在这种情况下,您的代码是有意义的:如果try{}块中的代码会抛出NumberFormatException之外的任何其他异常。只有当它是一个未检查的异常(您不需要捕获的异常)时,这才是可能的。编译器无法知道或检查这一点,因此,除非为其编写第二个catch块,否则不允许使用此类代码。(如果你现在感到困惑:忘记我说的话,这对你的任务并不重要)

    下面是这样一个例子:

    public float parseFloat(String s){
       float f = 0.0f;
       try{
          SomeOtherClass.doStuffWhichFailsWithRuntimeException();
          return f;
       }
       catch(NumberFormatException nfe){
           // will not run, because the thrown exception is not of type NumberFormatException
       }catch(Exception e){
           // any other failure besides NumberFormatException
           // considered bad practice: If you do not know what fails, do not try to recover from it, it's most likely very bad.
          return f;
       }
       finally { 
          // this will run after the catch block was run
          System.out.println("finally");  
       }
    
       // theoretically reachable, but compiler does not allow it because he cannot check it.
       //return f ;
    }
    
  2. # 2 楼答案

    如果发生异常,则运行catch块,返回f,最后运行下一个块。 最后

    return f;

    永远都联系不到