在catch块中没有抛出异常的异常

sbo*_*ose 2 java exception-handling divide-by-zero

在Java中使用异常处理时,我注意到在Java中的catch块中执行某些非法运行时操作时不会抛出异常.

这是语言中的错误还是我错过了什么?有人可以调查一下 - 因为为什么没有从catch块中抛出异常.

public class DivideDemo {

    @SuppressWarnings("finally")

    public static int divide(int a, int b){

    try{
       a = a/b;
    }
    catch(ArithmeticException e){
       System.out.println("Recomputing value");

       /* excepting an exception in the code below*/
       b=0;
       a = a/b;
       System.out.println(a);
    }
    finally{
      System.out.println("hi");
      return a;
    }
  }    
  public static void main(String[] args) {
     System.out.println("Dividing two nos");
     System.out.println(divide(100,0));
  }
Run Code Online (Sandbox Code Playgroud)

}

Tom*_*icz 12

这是语言中的错误还是我错过了什么?

这是因为你returnfinally块中有声明:

finally {
  System.out.println("hi");
  return a;
}
Run Code Online (Sandbox Code Playgroud)

return语句有效地吞并异常并使用返回值" 覆盖它 ".

也可以看看

  • 如果删除@SuppressWarnings("finally"),则会看到Eclipse警告:"finally块无法正常完成".正确的方法是避免警告不要压制它. (2认同)