欢迎来到天天文库
浏览记录
ID:48368271
大小:60.00 KB
页数:16页
时间:2019-11-28
《Java基础异常处理).doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、Java异常处理异常:程序运行时发生的非正常情况发生异常程序意外终止,控制权返回给调用者Java的异常类:Throwable(java异常的根类)—Error系统级错误一般不能恢复—Exception程序的实现过程中的异常运行时异常指在程序运行中不一定要扑获的异常比如:NullPointerExceptionArraylndexOutOfBoundsExceptionArithmeticException非运行时异常:指程序运行中一定要扑获的异常比如:SQLExceptionIOExceptionClassNotFou
2、ndExceptionpublicclassTestException{publicinttestException(inta,intb){intarr[]={1Z5,3Z8};try{System.out.printIn(arr[6]);returna/b;}catch(ArithmeticExceptione){System.out:.printin("分母不能为零、1!"+0.toStringO);return-1;}catch(ArraylndexOutOfBoundsExceptionae){ae.print
3、StackTrace();//打印错误堆栈信息System・out・printin("数组下标越界”);return-1;}catch(Exceptionex){System,out.printin(”我的任务是扑获前面的catch没有扑获的异常“);return-1;}finally{System,out.printin(“我是无论如何都要执行的代码”);publicstaticvoidmain(String[]args){TestExceptiontest=newTestException();intresult=
4、test・亡0$七£乂(:曲亡:1011(8,0);if(result>-l){System.outz.printIn("运彳亍正‘常结果:"^result);}else{System・out・printin("出现异常”);}System.out・printin(“程序往下执行”);使用多重catch子句要注意:在前面的异常级别不能大于后者finally是异常处理语句结构的一部分,表示无论什么情况都要执行的模块finally语句的主要作用是在try或catch转到其他部分前做的一些“善后”工作。比如:关闭打开的文件,
5、释放链接.内存等系统资源。throw关键字用来抛出一个异常。程序会在throw语句后立即终止staticvoidtest(){try{thrownewNullPointerException("抛出空指针异常”);//抛出一个异常}catch(NullPointerExceptione){System,out.printin(“扑获空指针异常”);throwe;//再次抛出此异常publicstaticvoidmain(String[]args){try{test();}catch(NullPointerExcepti
6、one){System,out・println(“扌卜获”+e);throws关键字throws标明方法中可能抛出的各种异常但不处理它,即回避此异常,而交给调用者处理publicclassTestExce{publicstaticvoidmain(String[]args){TestExtest=newTestEx();try{test・get(1,0);}catch(Exceptione){e.printStackTrace();}}}classTestEx{publicvoidget(intazintb)throw
7、sException{intc=a/b;System,out.printin(n这个方法可能会产生异常,请调用者处理”+c);自定义异常publicclassTestMyException{publicvoidtestMyException(intval)throwsMyExceptionif(val<0){thrownewMyException(HtB现异常,参数不能小于零");}else{System.out・println(val);}}publicstaticvoidmain(String[]args){Tes
8、tMyExceptiontesnewTestMyException();try{test.TestMyException⑴;}catch(MyExceptione){System.out.printIn(e•getMsg());classMyExceptionextendsExceptionprivateStringmsg;pub
此文档下载收益归作者所有