Throwable是类,Exception和Error都继承了该类
所以在捕捉的时候,也可以使用Throwable进行捕捉
如图: 异常分Error和Exception
Exception里又分运行时异常和可查异常。
public class TestException {
public static void main(String[] args) {
File f=new File("d:/l.txt");
try {
System.out.println("试图打开文件");
new FileInputStream(f);
//使用Throwable进行异常捕获
} catch (Throwable a) {
a.printStackTrace();
System.out.println("打开文件失败");
}
}
}
在方法声明上,可以抛出指定的异常,比如FileNotFoundException
那么能否抛出Throwable这个类?
这个方法的调用者又该如何处理?
public class Demo01 {
public static void main(String[] args) {
try{
method();
}catch (Throwable a){
System.out.println("出现异常,请检查");
a.printStackTrace();
}
}
private static void method() throws Throwable{
int num=1/0;
System.out.println(num);
}
}
可以抛出Throwable,因为是父类,但是catch方法也要捕捉 Throwable。