异常处理机制
异常处理机制
- 捕获异常
- 处理异常
- 处理异常的关键字:try,catch,finally,throw,throws
package Demo04;public class Application {public static void main(String[] args) {int a = 1;int b = 0;//System.out.println(a/b);//可以通过ctrl+alt+t快捷捕获异常//要捕获多个异常,要从小到大try{//监控区域if(b==0) {//主动抛出异常 throw throws这两种差别很大throw new ArithmeticException();}System.out.println(a/b);}catch (Exception e) {System.out.println("Exception");}catch(Error e){//捕获异常 里面的参数就是想要捕获的参数类型//catch可以设置多个//最大的异常要设置再后面 否则无法执行下面的//System.exit(1);实现程序停止e.printStackTrace();//打印错误栈信息System.out.println("Error");}finally {//处理善后工作System.out.println("finally");}//finally 可要可不要finally,用于假设IO流,资源关闭}
}输出结果为:
Exception
finally
上面的代码也可以通过方法定义以其他形式来实现。
如下演示
package Demo04;import Demo02.Test;public class Application {public static void main(String[] args) {try {new Application().test(1,2);} catch (ArithmeticException e) {//想办法把错误在catch中处理掉throw new RuntimeException(e);}}//如果在方法中处理不了这个异常,在方法上抛出异常,就是throws的使用体现public void test(int a,int b) throws ArithmeticException{if(b==0) {//主动抛出异常 一般再方法中使用// throw throws这两种差别很大throw new ArithmeticException();}System.out.println(a/b);}
}