try 和 finally 给出没有返回语句的异常,但是在方法中写入返回语句时没有异常

2022-01-19 00:00:00 return java try-finally

请解释为什么异常出现在第一个程序中,但没有出现在第二个程序中.

Please explain why Exception comes in first program but not in second program.

1) read 方法中没有返回语句

1) without return statement in read method

class Example
{   
    public static void read()
    {
        try
        {
             int i = 9/0;
        }
        finally
        {
              System.out.println("This proogram is giving exception");
        }       
    }

    public static void main(String[] fel)
    {
         read();
    }
}

2)read方法中带有return语句

2)with return statement in read method

class Example
{   
    public static void read()
    {
         try
         {
               int i = 9/0;
         }
        finally
        {
               System.out.println("This proogram is not giving exception");
               return;
        }       
    }

    public static void main(String[] fel)
    {
          read();
    }
}

推荐答案

分支语句(return ,goto )不能在finally内部使用,因为执行这样的语句会使finally之前执行的其他指令无效.

Branching statements(return ,goto ) should no be used inside finally because execution of such statement nullifies other instructions which are executed before finally.

Java 语言规范 说:如果 try 块的执行由于任何其他原因 R 突然完成,则执行 finally 块,然后有一个选择:

The Java Language Specification says : If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:

  1. 如果 finally 块正常完成,则由于原因 R,try 语句会突然完成.
  2. 如果 finally 块由于原因 S 突然完成,则 try 语句由于原因 S 突然完成(并且原因 R 被丢弃).

注意 - finally 块中的 return 语句将导致 try 或 catch 块中可能引发的任何异常被丢弃.

Note - A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.

相关文章