欢迎来到天天文库
浏览记录
ID:40556973
大小:62.50 KB
页数:14页
时间:2019-08-04
《Java基础(异常处理)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Java异常处理异常:程序运行时发生的非正常情况发生异常程序意外终止,控制权返回给调用者Java的异常类:Throwable(java异常的根类)―Error系统级错误一般不能恢复―Exception程序的实现过程中的异常运行时异常指在程序运行中不一定要扑获的异常比如:NullPointerExceptionArrayIndexOutOfBoundsExceptionArithmeticException非运行时异常:指程序运行中一定要扑获的异常比如:SQLExceptionIOExceptionClassNotFoundExceptionpub
2、licclassTestException{publicinttestException(inta,intb){intarr[]={1,5,3,8};try{System.out.println(arr[6]);returna/b;}catch(ArithmeticExceptione){System.out.println("分母不能为零"+e.toString());return-1;}catch(ArrayIndexOutOfBoundsExceptionae){ae.printStackTrace();//打印错误堆栈信息System
3、.out.println("数组下标越界");return-1;}catch(Exceptionex){System.out.println("我的任务是扑获前面的catch没有扑获的异常");return-1;}finally{System.out.println("我是无论如何都要执行的代码");}}publicstaticvoidmain(String[]args){TestExceptiontest=newTestException();intresult=test.testException(8,0);if(result>-1){Sys
4、tem.out.println("运行正常结果:"+result);}else{System.out.println("出现异常");}System.out.println("程序往下执行");}}使用多重catch子句要注意:在前面的异常级别不能大于后者finally是异常处理语句结构的一部分,表示无论什么情况都要执行的模块finally语句的主要作用是在try或catch转到其他部分前做的一些“善后”工作。比如:关闭打开的文件,释放链接、内存等系统资源。throw关键字用来抛出一个异常。程序会在throw语句后立即终止staticvoidte
5、st(){try{thrownewNullPointerException("抛出空指针异常");//抛出一个异常}catch(NullPointerExceptione){System.out.println("扑获空指针异常");throwe;//再次抛出此异常}}publicstaticvoidmain(String[]args){try{test();}catch(NullPointerExceptione){System.out.println("扑获"+e);}}throws关键字throws标明方法中可能抛出的各种异常但不处理它,即
6、回避此异常,而交给调用者处理publicclassTestExce{publicstaticvoidmain(String[]args){TestExtest=newTestEx();try{test.get(1,0);}catch(Exceptione){e.printStackTrace();}}}classTestEx{publicvoidget(inta,intb)throwsException{intc=a/b;System.out.println("这个方法可能会产生异常,请调用者处理"+c);}}自定义异常publicclassTe
7、stMyException{publicvoidtestMyException(intval)throwsMyException{if(val<0){thrownewMyException("出现异常,参数不能小于零");}else{System.out.println(val);}}publicstaticvoidmain(String[]args){TestMyExceptiontest=newTestMyException();try{test.testMyException(1);}catch(MyExceptione){System.o
8、ut.println(e.getMsg());}}}classMyExceptionextendsException{privateSt
此文档下载收益归作者所有