我不断收到错误:TestException.java:8:错误:未报告的异常Throwable;必须被抓住或宣布被抛出
抛出新的ParentException()。initCause(new ChildException()。initCause(new SQLException()));
任何想法,我知道一些微不足道的东西遗失了,我不会在我的脑海中轻易想到,谢谢,不要从源头上获取面值,我只是想让我理解。
import java.sql.SQLException;
public class TestException{
public static void main(String[] args) {
try{
throw new ParentException().initCause(new ChildException().initCause(new SQLException()));
}
catch(ParentException | ChildException | SQLException e){
e.printStackTrace();
try{
Thread.sleep(10*1000);
}
catch(Exception et){
;
}
}
}
}
class ParentException extends Exception{
public ParentException(){
super("Parent Exception is called");
}
}
class ChildException extends Exception{
public ChildException(){
super("Child Exception is called");
}
}
答案 0 :(得分:1)
initCause
会返回Throwable
。
这意味着您实际上是在抛出Throwable
而不是ParentException
,因此编译器抱怨您正在抛出Throwable
但是没有抓住它。
您可以通过更改ParentException
和ChildException
来解决此问题,这样他们不仅会收到错误消息,还会收到错误消息。然后,您可以拨打Exception
constructor that receives a message and a cause
答案 1 :(得分:1)
initCause()将抛出 Throwable 对象,因此你应该捕获该异常
catch (Throwable e)
{
e.printStackTrace();
}
答案 2 :(得分:1)
仅因为initCause
返回Throwable
个实例:
public synchronized Throwable initCause(Throwable cause)
虽然catch子句无法捕获任何Throwable
引用。您可以添加Throwable以及其他例外。
try {
throw new ParentException().initCause(new ChildException().initCause(new SQLException()));
} catch (ParentException | ChildException | SQLException e) {
e.printStackTrace();
try {
Thread.sleep(10 * 1000);
} catch (Exception et) {
;
}
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
或者只是捕获Throwable,如果你想捕获所有throwables,包括提到的三个异常和所有其他错误,延伸Throwable的异常
try {
throw new ParentException().initCause(new ChildException().initCause(new SQLException()));
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 3 :(得分:0)
initCause(Throwable cause)
函数返回Throwable
:public synchronized Throwable initCause(Throwable cause)
的对象,所以当你执行throw new ParentException().initCause(new ChildException().initCause(new SQLException()));
时,你基本上正在执行throw ( new ParentException().initCause(new ChildException().initCause(new SQLException())) ) ;
,所以你正在做throw <ThrowableObject>
,因此您必须捕获Throwable
的例外情况。
try {
throw new ParentException().initCause(new ChildException().initCause(new SQLException()));
} catch (Throwable e) {
e.printStackTrace();
try {
Thread.sleep(10*1000);
} catch(Exception ex) {}
您可以通过多种方式解决此问题,我认为通过<{1}}和ParentException
中的构造函数重载
ChildException
以及public ParentException(Throwable cause) {
super("Parent Exception is called", cause);
}
的类似版本并使用
ChildException
通过执行以下操作,而不是throw new ParentException(new ChildException(new SQLException()));
,或
initcause()
注意:您只需要捕获try {
ParentException p = new ParentException();
p.initCause(new ChildException().initCause(new SQLException()));
throw p;
} catch (ParentException e) {
e.printStackTrace();
try{
Thread.sleep(10*1000);
} catch(Exception ex) {}
而不需要捕获其他异常,因为它是唯一可能会被ParentException
体内抛出的异常。试图捕获其他异常(不是try
的超类)会给出错误,即您试图捕获永远不会抛出的异常。