可抛构造函数

Throwable constructors

Throwable constructors 的 4 种类型是:-

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.

来自ArithmeticException

下面没有构造函数,这就是为什么它给你编译时错误:

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);

如果您检查 JavaDoc 中的 ArithmeticException

http://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html

您将看到:

Constructor and Description

ArithmeticException() Constructs an ArithmeticException with no detail message. ArithmeticException(String s) Constructs an ArithmeticException with the specified detail message.

因此 none 个构造函数已实现:

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())