码迷,mamicode.com
首页 > 编程语言 > 详细

java7 异常处理增强

时间:2020-03-23 22:03:06      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:this   异常处理   期望   char   冗余   字符   竖线   void   ons   

在Java 7发行版中,oracle在异常处理机制上也做了一些不错的更改。这些主要是改进的catch块多余的throws子句。让我们看看他们是如何改变的。

1.改进了Java 7中的catch块

在此功能中,现在您可以在单个catch块中捕获多个异常。在Java 7之前,您只能在每个catch块中仅捕获一个异常。
要指定期望的例外列表,使用竖线(‘|‘)字符。
Java程序可在单个catch块中捕获多个异常。

try
{
    //Do some processing which throws NullPointerException;
    throw new NullPointerException();
}
//You can catch multiple exception added after ‘pipe‘ character
catch( NullPointerException npe | IndexOutOfBoundsException iobe )
{
       throw ex;
}

如果一个catch块处理一个以上的异常类型,则该**catch参数是隐式的final**。在此示例中,catch参数exfinal,因此您不能在catch块内为其分配任何值。

2.?Java 7中的冗余抛出子句

此功能使您免于在方法声明中使用throws子句。参见下面的示例:

public class MultipleExceptionsInCatchBlock {
 
    public static void main(String[] args)
    {
            sampleMethod();
    }
 
    public static void sampleMethod()
                    //throws Throwable  //No need to do this
    {
        try
        {
            //Do some processing which throws NullPointerException; I am sending directly
            throw new NullPointerException();
        }
        //You can catch multiple exception added after ‘pipe‘ character
        catch(NullPointerException | IndexOutOfBoundsException ex)
        {
            throw ex;
        }
        //Now method sampleMethod() do not need to have ‘throws‘ clause
        catch(Throwable ex)
        {
            throw ex;
        }
    }
}

java7 异常处理增强

标签:this   异常处理   期望   char   冗余   字符   竖线   void   ons   

原文地址:https://www.cnblogs.com/qingmiaokeji/p/12555359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!