Java 捕获和抛出异常
try ,catch ,finally ,throw ,throws
//假设要捕获多个异常:从小到大--- (Exception,Error) ,Throwable
/* try{ //try监控区域
System.out.println(a/b);
}catch (Exception e){ //catch想要捕获异常的类型!
System.out.println("除数不能为零!");
}catch(Error e){ //所有错误必须首字母大写
System.out.println("error");
} catch(Throwable t){
System.out.println("throwable");
}finally { //处理善后工作
System.out.println("finally");
}
*/
注意: 如果存在多个catch () {} , 异常类型必须从小到大,
顺序:(Exception,Error) ,Throwable
若:Throwable 在前,则后面异常无法执行,程序报错。
package com.study.exception;
public class text {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new text().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
//假设要捕获多个异常:从小到大--- (Exception,Error) ,Throwable
/* try{ //try监控区域
System.out.println(a/b);
}catch (Exception e){ //catch想要捕获异常的类型!
System.out.println("除数不能为零!");
}catch(Error e){ //所有错误必须首字母大写
System.out.println("error");
} catch(Throwable t){
System.out.println("throwable");
}finally { //处理善后工作
System.out.println("finally");
}
*/
}
//假设这个方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b) throws ArithmeticException{ //在方法上抛出异常--throws,必须要用try{},catch(){};
if(b==0){
throw new ArithmeticException(); //在方法内抛出异常--throw
}
}
}