关于多个“catch”的问题 [英] Question about multiple 'catch'

查看:97
本文介绍了关于多个“catch”的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我为什么这个类的输出是'xa'?

Can anyone tell me why the output of this class is 'xa'?

为什么其他异常(RuntimeException和Exception)不会被捕获? p>

why the other exception(RuntimeException and Exception ) won't be caught?

public class Tree {
    public static void main(String... args) {
        try
        {
            throw new NullPointerException(new Exception().toString());
        }
        catch (NullPointerException e)
        {
            System.out.print("x");
        }
        catch (RuntimeException e)
        {
            System.out.print("y");
        }
        catch (Exception e)
        {
            System.out.print("z");   
        }        
        finally{System.out.println("a");}
    }
}


推荐答案

抛出的唯一异常是throw语句旁边的异常。另一个被创建,但没有抛出。不可能同时抛出两个异常。

The only exception thrown is the one right next to the throw statement. The other is created but not thrown. It is not possible to throw two exceptions simultaneously.

通常当异常在另一个异常的构造函数中传递时,它是指示该异常是这个异常的原因一。但是,实际抛出的唯一异常是throw语句旁边的一个例外。

Typically when an exception is passed in the constructor of another exception it is to indicate that the that exception is the cause of this one. However, the only exception actually being thrown is the one next to the throw statement.

在这种情况下,NullPointerException不支持其构造函数中的异常,因为它不是由其他异常,它是由null引用引起的。在其他情况下,这是因为在1.4之前没有在Java中引入异常链接,所以一些传统的异常类没有被修改为新的构造函数。在这种情况下,您可以使用 initCause(Throwable)方法来执行构造函数的操作。

In this case NullPointerException does not support an Exception in its constructor because it is not caused by other exceptions, it is caused by null references. In other cases it is because exception chaining was not introduced in Java until 1.4, so some legacy exception classes didn't get retro-fitted with new constructors. In that case you can use the initCause(Throwable) method to do what the constructor would have done.

这篇关于关于多个“catch”的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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