4 种类型的 Throwable 构造函数
是:-
Throwable() : Constructs a new throwable with null as its detail message.
Throwable(String message) : Constructs a new throwable with the specified detail message.
Throwable(String message, Throwable cause) : Constructs a new throwable with the specified detail message and cause.
Throwable(Throwable cause) : Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString())
在一段代码中,前两个构造函数类型工作正常,但其他两个类型报告编译时错误。
IOException e = new IOException(); //Working properly
ArithmeticException ae = new ArithmeticException("Top Layer"); //Working properly
ArithmeticException ae = new ArithmeticException("Top Layer", e); //Not working
ArithmeticException ae = new ArithmeticException(e); //Not working
最后两个声明报错
No suitable constructors found for ArithmeticException
我使用的是 JDK 8
为什么最后两个声明报错? 另外我该如何让它们工作?
最佳答案
因为ArithmeticException
是一个未经检查的异常并且来自RuntimeException
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
没有如下所示的构造函数,这就是为什么它会给你编译时错误:
AithmeticException ae = new ArithmeticException("Top Layer", e); //Not working
ae = new ArithmeticException(e); //Not working
更好地使用RuntimeException为此:
RuntimeException ae = new RuntimeException("Top Layer", e);
ae = new RuntimeException(e);
关于java - 可抛出的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915610/