java - 可抛出的构造函数

标签 java exception constructor throwable

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.

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

关于java - 可抛出的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915610/

相关文章:

java - 在另一个字符串中找到该字符串的字符有多少次

java - 使用 Apache POI 更改图像布局或包装在 DOCX 中

java - 在字符串中按字母顺序对字符进行排序

c# - Task.Run 和 Task.Factory.StartNew 之间不同的异常处理

java - Java 应用程序中的 PKIX 路径构建失败

java - 构造函数调用必须是具有继承的构造函数中的第一个语句

java - Intent 构造函数的上下文参数

java - Spring JPA Repository n+1 问题,EBEAN 替代方案

java - 异常处理和初始化

c++ - 使用 cin 将输入作为函数参数传递