【问题标题】:Exception not thrown on divide by zero in catch block在 catch 块中除以零时未引发异常
【发布时间】:2012-10-16 18:35:43
【问题描述】:

在玩 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));
  }

}

【问题讨论】:

    标签: java exception-handling divide-by-zero


    【解决方案1】:

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

    这是因为您的 finally 块中有 return 语句:

    finally {
      System.out.println("hi");
      return a;
    }
    

    这个return 语句有效地吞下异常并“覆盖它”并返回值。

    另见

    【讨论】:

    • 感谢@Tomasz,所以从技术上讲,如果有 return 声明,任何事情都可以在 catch 内完成。这不应该是语言的缺陷吗? (只是头脑风暴)
    • @SHOUBHIKBOSE -- 它“按设计工作”。在 finally 块中有一个 return 语句是一个非常糟糕的主意,但是语言会让你这样做。 (没有计算机语言可以阻止你做愚蠢的事情。)
    • 谢谢。我想知道为什么语言允许这样做? [我的意思是什么可能是这个设计决定的原因]
    • @SHOUBHIKBOSE 例如,您在 try 代码部分中打开一个 Stream 并在 finally 中关闭它(即使在 try 块中出现错误,也可以释放资源,+1!),但是你在 try 块的末尾有一个 return,那么资源应该保存在内存中吗?
    • 如果删除 @SuppressWarnings("finally"),您会看到 Eclipse 警告:“finally 块未正常完成”。正确的方法是避免警告不要压制它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多