【问题标题】:Why value from inside of "try" is printed during catching the exception? [duplicate]为什么在捕获异常期间会打印“try”内部的值? [复制]
【发布时间】:2018-07-12 01:58:13
【问题描述】:

我有这样的代码:

class ExceptionTest{

    public Integer divide(int a, int b) {
        try {           
            return a/b;         

        }finally {
            System.out.println("Finally");
        }
   }


}

public class Three {

    public static void main(String[] args) {


        ExceptionTest test = new ExceptionTest();

        try {
            System.out.println(test.divide(10, 0));         
        }catch(Exception e) {
            System.out.println("DIVIDED BY 0!");
        }
   }
}

当我运行它打印的代码时:

Finally 
DIVIDED BY 0!

这是为什么呢?如果捕获到异常,则不应仅“除以 0!”打印出来?

编辑:

我知道 finally 总是被打印出来的,但我的意思是在 main 的 try-catch 块中调用了名为“divide”的方法中的 try-finally。因此,如果捕获到异常,为什么会打印 try-catch 中的某些内容?即使我的 ExceptionTest 类看起来像这样:

class ExceptionTest{

    public Integer divide(int a, int b) {                   

           System.out.println("Finally")

            return a/b;     
   }


}

所以没有try-finally块并且抛出异常,我仍然有

Finally
Divided by 0!

【问题讨论】:

  • finally 块的全部意义在于绝对保证其中的代码可以运行。
  • 最终将被执行。这就是拥有该块类型的全部意义。
  • 你能解释一下为什么你认为finally不应该被执行吗?
  • @BoristheSpider 我已将我的问题编辑得更具体,我认为这不是您标记的重复问题。
  • @Gregory 您的编辑没有多大意义,因为在进行除法之前您有System.out.println("Finally")。所以显然打印将在抛出异常之前执行。异常发生在a/b,此时您的方法因异常而停止。

标签: java exception try-catch try-catch-finally finally


【解决方案1】:

finally 块中的代码始终运行,即使代码正确执行。您需要改用catch,它仅在发生错误时执行。

try { /* Runs first, and stops executing if an Exception's thrown. */  }
catch(Exception e) { /* Run whenever an Exception's thrown. */ }
finally { /* Always runs. */ }

您还需要确保从catch 子句返回一个值。像

try {
    return a / b;
} catch (ArithmeticException ae) {
    System.err.println("Cannot divide by zero!");
    return -1;
}

【讨论】:

    【解决方案2】:

    文档告诉我们finally-block

    finally 块总是在 try 块退出时执行。这样可以确保即使发生意外异常也会执行 finally 块。

    因此,即使您除以 0(这会引发异常),也会到达 finally 块。

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多