异常
异常
捕获异常
//假设要捕获多个异常:从小到大Error<Exception<Throwable
//快捷键ctrl+alt+t
try {//try 监控区域
System.out.println(a/b);
}catch(Error e){//catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
}catch(Exception e){
System.out.println("Exception"); 输出结果: //Exception
}catch(Throwable t){ //finally
System.out.println("Throwable");
}finally {//处理善后工作 可以不要
System.out.println("finally");
}
主动抛出异常
public static void main(String[] args) {
new test2().test(1,0);
}
public void test(int a,int b){
if(b==0){//throw throws
throw new ArithmeticException();//一般在方法中主动抛出异常
}
}
假设在方法中处理不了这个异常 在方法上抛出异常
try {
new test2().test(1,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
public void test(int a,int b)throws ArithmeticException{//在方法上抛出异常
if(b==0){//throw throws
throw new ArithmeticException();//一般在方法中主动抛出异常
}

浙公网安备 33010602011771号