Throwable constructors
的4种类型是: -
Throwable(): 构造一个新的throwable,其中包含null作为其详细消息。
Throwable(String message): 使用指定的详细消息构造一个新的throwable。
Throwable(String message,Throwable cause): 使用指定的详细消息和原因构造一个新的throwable。
Throwable(Throwable cause): 构造一个具有指定原因的新throwable和一个详细消息(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
最后两个声明是报告错误
找不到ArithmeticException
的合适构造函数
我正在使用JDK 8
为什么最后两个声明报告错误? 另外我如何让它们起作用?
答案 0 :(得分:2)
因为ArithmeticException
是未经检查的例外而来自RuntimeException
RuntimeException及其子类是未经检查的异常。 未经检查的异常不需要在方法或构造函数的throws子句中声明,如果它们可以通过执行方法或构造函数抛出并在方法或构造函数边界外传播。
下面没有构造函数,这就是为什么它给你编译时错误:
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);
答案 1 :(得分:1)
如果检查JavaDoc for ArithmeticException
http://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
你会看到:
构造函数和描述
ArithmeticException()构造一个 ArithmeticException没有详细消息。 ArithmeticException(字符串 s)构造具有指定细节的ArithmeticException 消息。
所以没有实现这些构造函数:
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())