java基础33-异常处理机制
- 抛出异常
- 捕获异常
五个关键字:
- try
- catch
- finally
- throw
- throws
package com.exception;
public class Test{
public static void main(String[] args){
try{
new Test().test(1,0);
}catch(ArithmeticException){
e.printStackTrace();
}
/*
try{//监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//捕获异常 只能捕获对应异常
System.out.println("程序出现异常");//程序出现异常
}catch(Exception e){
System.out.println("Exception");//Exception
}catch(Throwable t){//捕获多个异常时最大的异常写在最下面
System.out.println("Throwable");//Throwable
}
}finally{//处理善后工作
System.out.println("finally");//没捕获到异常finally也执行
}//finally可以不写 可用于IO资源关闭
}
*/
}
//假设在这个方法中处理不了这个异常,方法上抛出异常
public void test(int a,int b)throws ArithmeticException{
if(b==0){//主动抛出异常,一般在方法中使用
throw new ArithmeticException();
}
System.out.println(a/b);
}
}
//CTRL+alt+t自动生成