尝试并最终给出不带return语句的异常,但是在方法中编写return语句时也没有异常 [英] try and Finally giving exception with no return statement , but there is no exception when return statement is written in method

查看:93
本文介绍了尝试并最终给出不带return语句的异常,但是在方法中编写return语句时也没有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释为什么异常出现在第一个程序中而不出现在第二个程序中.

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

1)在读取方法中没有return语句

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),因为执行此类语句会使最终要执行的其他指令无效.

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块正常完成,则try语句由于原因R突然完成.
  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.

这篇关于尝试并最终给出不带return语句的异常,但是在方法中编写return语句时也没有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆