最近学习了Java的异常链机制,发现了一个问题,就是作者实现Java异常链的时候总是在方法定义处throws方法体中已经throw过实例的异常类,显得有些赘余,我想请问这是在干什么,throws和throw不配套使用也不会出错,这样做只是为了什么?以为了后能看得懂?
public class ExceptionList {
public void firstStep() throws MyException{
throw new MyException();
}
//这里又throws了catch子句里已经抛出的异常
public void SecondStep() throws AutoDefinedRuntimeException{
try {
ExceptionList eList = new ExceptionList();
eList.firstStep();
}
catch(MyException me1) {
//me1.getMessage();
me1.printStackTrace();
throw new AutoDefinedRuntimeException(me1);//抛出更高级的异常
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
ExceptionList eList = new ExceptionList();
eList.SecondStep();
}
catch(AutoDefinedRuntimeException me2) {
//me2.getMessage();
me2.printStackTrace();
}
}
}
既然 catch 了但是不处理而往上层跑,那么就没有必要用 catch 直接抛就可以了。
Java 语法规定的代码中但凡使用 throws 抛出异常的都需要在方法定义的时候声明。
如果不想在方法中进行捕获,可以在方法声明时利用throws声明进行抛出,将其交给自己的“上级”(调用此方法的程序)处理。在catch{}模块中用throw再次抛出了一个异常是为了监控异常是否被正常抛出(小白见解)