欢迎来到天天文库
浏览记录
ID:43195670
大小:110.00 KB
页数:17页
时间:2019-10-02
《Java语言程序设计基础教程课件(第9章)》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Java程序设计——第9章java异常处理第9章 异常处理了解异常处理机制和办法自定义异常类classTest{publicintdevide(intx,inty){intresult=x/y;returnx/y;}}PublicclassException1{publicstaticvoidmain(Stringargs[]){intresult=newTest().devide(3,0);System.out.println(“result=”+result);}}9.1java异常处理异常就是在程序的运行过程中所发生的异常事件,它中断程序的正常执行。当程序运行
2、出现异常时,Java运行环境将产生一个异常对象,若有相应的异常处理器处理相应异常,将转入相应异常处理代码,否则程序提前结束Java异常处理机制1——try…catch…[finally…]publicclassException2{publicstaticvoidmain(Stringargs[]){try{intresult=newTest().devide(3,0);System.out.println(“result=”+result);}catch(ArithmeticExceptione){System.out.println(e.getMessage()
3、);}finally{System.out.println(“finally”);}System.out.println(“outoftry-catch”);}}Finally和finally代码块之后的语句的不同之处:当在try——catch代码块中使用了return语句退出当前方法或break跳出某个循环前,finally代码快都要执行,而finally代码块之后的语句不会执行Java异常处理机制2——方法使用throws抛出异常classTest{publicintdevide(intx,inty)throwsArithmeticException{intre
4、sult=x/y;returnx/y;}}publicclassTestException{publicstaticvoidmain(Stringargs[]){intresult=newTest().devide(3,0);System.out.println(“result=”+result);}}编译异常!!编译器强制程序对可能发生异常的调用语句放入try-catch中classTest{publicintdevide(intx,inty)throwsException{。。。}}publicclassException3{publicstaticvoidma
5、in(Stringargs[]){try{intresult=newTest().devide(3,0);System.out.println(“result=”+result);}catch(Exceptione){System.out.println(e.getMessage());}}}classTest{publicintdevide(intx,inty)throwsException{。。。}}publicclassTestException{publicstaticvoidmain(Stringargs[])throwsException{intresu
6、lt=newTest().devide(3,0);System.out.println(“result=”+result);}}Throws:向上即调用方法传递异常,直到适当方法捕获并处理java系统异常类层次在jdk中,所有的异常类都直接或间接地继承于Throwable类ThrowableErrorExceptionIllegalAccessErrorVirtualMachineErrorIOExceptionRuntimeExceptionArithmeticExceptionInterruptedExceptionIndexOutOfBoundsExcepti
7、onFileNotFoundExceptionEOFException可以自定义异常类吗?如何定义?类名功能描述ArithmeticException算术运算除数为零IndexOutofBoundException下标越界错误ArrayIndexOutofBoundsException数组元素下标越界错误StringIndexOutofBoundsException字符串下标越界错误ClassCastException类型强制转换异常NegativeArraySizeException数组的长度为负异常NullPointerException非法使用空指针异常J
此文档下载收益归作者所有