Error和Exception
- 什么是异常:
-
简单分类:
-
异常的体系结构
-
Error:
-
Exception
捕获和抛出异常
异常处理的五个关键字:
try catch finally throw throws
public class Demo01{
public static void main(String[] args){
int a = 1;
int b = 0;
//假设要捕获多个异常,则需要异常的类型从小到大写
try{//try监控区域
new Demo01().a();
System.out.println(a/b);
}catch (ArithmeticException e){//catch要捕获异常
System.out.println("程序出现异常,除数不能为0!");
}catch (Throwable e){
System.out.println("程序出现异常");
}finally {//处理善后的工作
System.out.println("finally");
}
//可以不要finally, 但是finally一般用来关闭一些资源
}
public void a(){
b();
}
public void b(){
a();
}
//假设在方法中,处理不了这个异常,则方法上抛出异常
public void test(int a,int b) throws Exception {
if (b==0){
throw new ArithmeticException();//主动抛出异常,一般用在方法中
}
}
}