publicclassTest{publicstaticvoidmain(String[] args){int a =1;int b =0;//finally可以不要,但是try catch 一定要try{//try可以监控区域,在try代码块中可以用catch来监控区域System.out.println(a/b);}catch(ArithmeticException e){//捕获异常,但必须先知道异常ArithmeticException 把它看做eSystem.out.println("程序出现异常,变量b不能为0");}finally{//不管出不出异常,都要执行finallySystem.out.println("finally");}}
catch可以多个
publicclassTest{publicstaticvoidmain(String[] args){int a =1;int b =0;try{System.out.println(a/b);}catch(Error e){//catch(想要捕获的异常类型,最高型为Throwable 然后为Error,Exception)System.out.println("Error程序出现异常");}catch(Exception e){//catch可以捕获多个异常,会层层递进捕获最合适的异常,要从小到大System.out.println("Exception程序出现异常");}catch(Throwable e){//catch要把最大的异常写在最后面System.out.println("Throwable程序出现异常");}finally{System.out.println("finally");}}}
//主动抛出异常throw用在方法里面 //主动抛出异常throws用在方法上
//主动抛出异常throw用在方法里面//主动抛出异常throws用在方法上publicclassTest3{publicstaticvoidmain(String[] args){try{newTest3().test(1,0);}catch(ArithmeticException e){
e.printStackTrace();//throw new RuntimeException(e);}}//假设这个方法中处理不了异常,方法上抛出异常publicvoid test (int a,int b)throwsArithmeticException{if(b==0){// throw在通常用在方法里面抛出异常thrownewArithmeticException();//主动抛出异常.通过throw来new一个方法报错的异常}System.out.println(a/b);}}