欢迎来到天天文库
浏览记录
ID:56527617
大小:273.00 KB
页数:16页
时间:2020-06-27
《java基础-异常处理课件.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、异常处理1什么是异常?publicclassExceptionRaised{publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2){intresult=operand1/operand2;returnresult;}publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();intresult=obj.calculate(9,0);S
2、ystem.out.println(result);}}OS异常情况异常程序突然终止并将控制交给操作系统在运行时发生的错误2ExceptionArithmeticExceptionNullPointerExceptionObjectThrowableErrorThreadDeathSQLExceptionRuntimeExceptionNumberFormatException……异常类的层次结构Throwable具有两个子类,它们是Exception:处理用户程序应当捕获的异常情况Error:Erro
3、r类的异常为内部错误,因此在正常情况下不期望用户的程序捕获它们AWTError3Java异常类文件结束EOFException找不到文件FileNotFoundExceptionI/O异常的根类IOException数字转化格式异常,比如字符串到float型数字的转换无效NumberFormatException不能加载所需的类ClassNotFoundException方法接收到非法参数IllegalArgumentException数组大小小于或大于实际的数组大小ArrayIndexOutOfBou
4、ndException尝试访问null对象成员NullPointerException许多java.lang异常的基类RuntimeException异常层次结构的根类Exception算术错误情形,如以零作除数ArithmeticException线程中断InterruptedException说明异常4手动引发异常指定由方法引发的异常tryfinallycatchthrowsthrow处理异常2-2要监控的程序语句包含在此块中以合理的方式捕获和处理异常释放资源等5try和catch块2-1tryca
5、tch异常执行catch后程序继续正常运行程序控制引发代码块单元6try和catch块2-2演示:示例1try和catch块的用法classExceptionRaised{/**构造方法.*/publicExceptionRaised(){}/***这个方法运行时将会产生一个异常.*@paramoperand1除法中的分子*@paramoperand2除法中的分母*@returnint返回除法的结果*/publicintcalculate(intoperand1,intoperand2){intresu
6、lt=operand1/operand2;returnresult;}}publicclassArithmeticException{/**构造方法.*/publicArithmeticException(){}publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();try{/*定义变量result以存储结果.*/intresult=obj.calculate(9,0);System.out.println(r
7、esult);}catch(Exceptione){System.err.println(“发生异常:"+e.toString());e.printStackTrace();}}}7finally块try块finally块catch块无异常异常try、catch和finally块的执行流程8异常处理块的一般形式try{//要监控错误的代码块methodGeneratingException();}catch(Exceptione){//Exceptione的异常处理程序}finally{//在try结束
8、前要执行的代码块cleanup();}9多重catch块3-1一段代码可能会生成多个异常当引发异常时,会按顺序来查看每个catch语句,并执行第一个类型与异常类型匹配的语句执行其中的一条catch语句之后,其他的catch语句将被忽略try{…….}catch(ArrayIndexOutOfBoundsExceptione){……}catch(Exceptione){……}10多重catch块3-2使用多重catch语句时,异常子类一定要位
此文档下载收益归作者所有