抛出异常
捕获异常
异常处理五个关键字:try、catch、finally、throw、throws
自定义异常:只需继承Exception
步骤:
1.创自定义异常类
2.方法中throw抛出或类上throws抛出或方法后throws抛出
3.try catch捕获并处理异常
package com.wuming.exception; public class Test { public static void main(String[] args) { int a=1; int b=0; try {//try监控区域 //System.out.println(a/b); new Test().a();//Exception in thread "main" java.lang.*Error,需用Throwable或error或exception捕获 }catch(ArithmeticException e){//catch捕获异常 System.out.println("程序出现异常,变量b不能为0"); }catch(Error e){ System.out.println("程序出现异常(用Error来看)");//一旦捕获异常(要看异常的分类走的),直接走finally }catch(Exception e){ System.out.println("程序出现异常(用Exception来看)"); }catch(Throwable e){//有多个捕获异常的关键字,顺序,只看Throwable必须放finally的前一个 System.out.println("程序出现异常(用Error来看)");//一旦捕获异常,直接走finally } finally {//处理善后工作 System.out.println("finally"); } //finally可以不要finally,但有finally一定会输出。假设有IO,资源要关闭 } public void a(){ b(); } public void b(){ a(); } }
package com.wuming.exception; public class Test1 { public static void main(String[] args) { try { new Test1().test(1,0); } catch (ArithmeticException e) {//在public void test(int a,int b)后面加 throws ArithmeticException,ctrl+alt+t后会出现ArithmeticException,不加throws ArithmeticException,ctrl+alt+t后会出现Exception e.printStackTrace(); } //throw用在方法中主动抛出异常//Exception in thread "main" java.lang.ArithmeticExceptionat com.wuming.exception.Test1.test(Test1.java:27)at com.wuming.exception.Test1.main(Test1.java:5) } /* public static void main(String[] args) { int a=1; int b=0; //try catch快捷键 ctrl+alt+t;先选中 try { if (b==0){ throw new ArithmeticException();//主动抛出异常用(throw和throws区别,后者用在方法上或类上,前者用在方法中,但这里没有用在方法中,不能抛出异常,看下面用在test()就抛出了) } System.out.println(a/b); } catch (Exception e) { // System.exit(1);//退出 System.out.println("Exception"); //e.printStackTrace();//打印错误的栈信息//java.lang.ArithmeticException: / by zeroat com.wuming.exception.Test1.main(Test1.java:9) } finally { System.out.println("finally"); } }*/ public void test(int a,int b) throws ArithmeticException{ if (b==0){// throw new ArithmeticException(); } System.out.println(a/b); } }