packagecom.exception;publicclassDemo01{publicstaticvoidmain(String[] args){// new Demo01().a();// System.out.println(11/0);// System.out.println()}// public void a(){// b();// }//// public void b(){// a();// }}
异常02:捕获和抛出异常
异常处理机制
抛出异常
捕获异常
异常处理五个关键字
try、catch、finally、throw、throws
packagecom.exception;publicclassTest{publicstaticvoidmain(String[] args){try{newTest().test(1,0);}catch(ArithmeticException e){
e.printStackTrace();}}//假设这方法中,处理不了这个异常。方法上抛出异常publicvoidtest(int a,int b)throwsArithmeticException{if(b==0){//throw throwsthrownewArithmeticException();//主动的抛出异常,一般在方法中使用}// System.out.println(a/b);}}/*
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常:从小到大!
try { //try监控区域
if (b==0){ //throw throws
throw new ArithmeticException(); //主动的抛出异常
}
System.out.println(a/b);
// new Test().a();
}catch (Error e){ //catch(想要捕获的异常类型!)捕获异常
// }catch (Throwable e){ //catch(想要捕获的异常类型!)捕获异常
// System.out.println("程序出现异常,变量b不能为0");
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
} finally { //finally处理善后工作
System.out.println("finally");
}
//finally 可以不要finally,假设IO,资源,关闭!
}
// public void a(){
// b();
// }
//
// public void b(){
// a();
// }
*/
packagecom.exception;publicclassTest2{publicstaticvoidmain(String[] args){int a =1;int b =0;//ctrl + alt + Ttry{System.out.println(a/b);}catch(Exception e){
e.printStackTrace();//打印错误的栈信息}finally{}}}