![第5章异常处理(13级)_第1页](http://file4.renrendoc.com/view/1f1237499633e4d4b2988cbbfb72b26b/1f1237499633e4d4b2988cbbfb72b26b1.gif)
![第5章异常处理(13级)_第2页](http://file4.renrendoc.com/view/1f1237499633e4d4b2988cbbfb72b26b/1f1237499633e4d4b2988cbbfb72b26b2.gif)
![第5章异常处理(13级)_第3页](http://file4.renrendoc.com/view/1f1237499633e4d4b2988cbbfb72b26b/1f1237499633e4d4b2988cbbfb72b26b3.gif)
![第5章异常处理(13级)_第4页](http://file4.renrendoc.com/view/1f1237499633e4d4b2988cbbfb72b26b/1f1237499633e4d4b2988cbbfb72b26b4.gif)
![第5章异常处理(13级)_第5页](http://file4.renrendoc.com/view/1f1237499633e4d4b2988cbbfb72b26b/1f1237499633e4d4b2988cbbfb72b26b5.gif)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第5章异常处理错误与异常致命性的错误(Error):如果程序进入了死循环,或递归无法结束,或内存溢出,这些现象称为错误。错误只能在编程阶段解决,运行时程序本身无法解决,只能依靠其它程序干预,否则会一直处于非正常状态。Java程序不做处理。非致命性的异常(Exception)
:如果运算时除数为0,或操作数超出数据范围,或打开一个文件时发现文件不存在,或欲装入的类文件丢失,或网络连接中断等,这些现象称为异常。在源程序中加入异常处理代码,当程序运行中出现异常时,由异常处理代码调整程序运行方向,使程序仍可继续运行直至正常结束。什么是异常在程序运行过程中发生的、会打断程序正常执行的事件称为异常(Exception),也称为例外。例如,零用作除数(产生算术异常ArithmeticException)、
在指定的磁盘上没有要打开的文件(产生文件未找到异常
FileNotFoundException)
数组下标越界(产生数组下标越界异常
ArrayIndexOutOfBoundsException)等常见异常importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in);age=sc.nextInt();System.out.println("年龄是"+age+"岁");System.out.println("程序结束");}}
RuntimeException(运行时异常):Java虚拟机在运行时生成的异常,如被0除等系统错误、数组下标超范围等,其产生比较频繁,处理麻烦,对程序可读性和运行效率影响太大。因此由系统检测,用户可不做处理,系统将它们交给缺省的异常处理程序(当然,必要时,用户可对其处理)。CheckedException(检查型异常):一般程序中可预知的问题,其产生的异常可能会带来意想不到的结果,因此Java编译器要求Java程序必须捕获或声明所有的非运行时异常。异常的分类importjava.io.*;publicclassaaa{publicstaticvoidmain(String[]args){inta;a=(int)System.in.read();System.out.println("a的值是"+a);}}检查型异常实例无法通过编译异常与异常类Java中定义了很多异常类。每个异常类都代表了一种运行错误。类中包含了该运行错误的信息和处理错误的方法等内容。异常类的层次为内部错误,因此在正常情况下不期望用户的程序捕获它们Java虚拟机在运行时生成的异常,由系统检测,用户可不做处理,系统将它们交给缺省的异常处理程序。程序中可预知的问题,可能会带来意想不到的结果,Java程序必须捕获或声明所有的非运行时异常。异常类的层次算术异常类型强制转换异常空指针异常数组负下标异常数组下标越界异常下标越界异常ArithmeticException:算术异常
ArrayIndexOutOfBandsException:数组下标越界异常
ArrayStoreException:数组存储异常
IOException:输入输出异常
FileNotFoundException:文件未找到异常
NullPointerException:空指针异常
ClassCastException:类型强制转换异常
如果使用了能够产生异常的方法而没有捕获和处理,程序将不能通过编译。
常见的异常当程序试图访问一个空对象(即没有实例化的对象)中的变量或方法,或一个空数组中的元素时,会发生该异常。如:
Strings;System.out.println(s.length());inta[];a[0]=0;
空指针异常NullPointerException当进行类型强制转换时,对于不能进行的转换操作,会发生该异常。例如:
Objectobj=newObject();
Strings=(String)obj;类型强制转换异常ClassCastException6.2异常处理机制
捕获异常声明抛出异常throwsTry-catch消极的处理方式积极的处理方式捕获异常捕获异常是通过try-catch-finally语句实现的。
tryfinallycatch要监控的程序语句包含在此块中以合理的方式捕获和处理异常释放资源等异常的捕获与处理try{〈语句1〉}catch(ExceptionType1e)
{〈语句2〉}……finally
{〈语句3〉}接受监视的程序块,在此区域内发生的异常,由catch中指定的程序处理;处理异常要处理的异常种类和标识符一定要执行,是异常处理的统一出口,可以省略。捕获异常
try语句
捕获异常的第一步就是用try{…}语句指定了一段代码,该段代码就是一次捕获并处理异常的范围。在执行过程中,该段代码可能会产生并抛弃一个或多个异常,因此,它后面的catch语句进行捕获时也要做相应的处理。处理异常
catch语句每个try语句必须伴随一个或多个catch语句,用于捕获try代码块所产生的异常并做相应的处理。catch语句有一个形式参数,用于指明其所能捕获的异常类型,运行时系统通过参数值把被抛弃的异常对象传递给catch语句。要根据具体的情况来选择catch语句的异常处理类型,一般应该按照try代码块中异常可能产生的顺序及其真正类型进行捕获和处理,尽量避免选择最一般的类型作为catch语句中指定要捕获的类型。也可以用一个catch语句处理多个异常类型,这时它的异常类型应该是这多个异常类型的父类,但这种方式使得在程序中不能确切判断异常的具体类型。统一出口
finally语句
捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流程转到程序的其他部分以前,能够对程序的状态作统一的管理。
无论try所指定的程序块中抛出或不抛出异常,也无论catch语句的异常类型是否与所抛出的异常的类型一致,finally所指定的代码都要被执行,它提供了统一的出口。通常在finally语句中可以进行资源的清除工作,如关闭打开的文件等。importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in); try{age=sc.nextInt();System.out.println("年龄是"+age+"岁");
}catch(InputMismatchExceptione){System.out.println("输入的数据不匹配");
}finally{System.out.println("程序结束");}}}异常的产生、捕获和处理importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in);
age=sc.nextInt();System.out.println("年龄是"+age+"岁");System.out.println("程序结束");}}异常类(Exception)的常用方法Exception()
构造详细消息为null的新异常。Exception(String
message)构造带指定详细消息的新异常。toString()方法显示的异常信息
java.lang.ArithmeticException:/byzerogetMessage()方法显示的异常信息
/byzeroprintStackTrace()方法显示的异常信息
java.lang.ArithmeticException:/byzero
atExceptionDemo.main(basdf.java:8)异常处理实例classExceptionRaised{
publicExceptionRaised(){}
publicintcalculate(intoperand1,intoperand2){intresult=operand1/operand2;returnresult;}
publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();intresult=obj.calculate(9,0);System.out.println(result);}}!在运行时发生的错误
解决方案一classExceptionRaised{
publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2){intresult=0;try{ result=operand1/operand2;}catch(Exceptione){System.err.println("发生异常:"+e.toString());e.printStackTrace();}returnresult;}
publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();intresult=obj.calculate(9,0);System.out.println(result);}}调用异常类的方法指明catch可以捕获并处理的异常类型classTest{ publicintdevide(intx,inty) { returnx/y; }
}classTestException
{ publicstaticvoidmain(Stringargs[]) { inti;
try{ Testt1=newTest(); i=t1.devide(3,0); System.out.println(i); }
catch(ArithmeticExceptione) { System.out.println(e.getMessage()); System.out.println("0做除数!"); } }}/byzero0做除数!实战
阅读下列程序代码,分析程序可能产生的异常情况,捕获并处理异常。publicclassExceptionDemo{intarray[]={1,2,3,4,5,6,7,8,9,0};publicvoidexceptest(intj){ for(inti=0;i<j;i++) {System.out.println("array["+i+"]="+array[i]);} }publicstaticvoidmain(Stringargs[]){ExceptionDemoex=newExceptionDemo();ex.exceptest(11);}}
importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in); try{age=sc.nextInt();System.out.println("年龄是"+age+"岁");
}catch(InputMismatchExceptione){System.out.println("输入的数据不匹配");
}System.out.println("程序结束");}}是否有其他异常?6.3人为抛出异常我们在程序中也可以生成自己的异常对象,也就是异常可以不是出错产生,而是人为地抛出。通过throw语句实现:ArithmeticExceptione=newArithmeticException();throwe;
thrownewArithmeticException();注意:抛出的异常必须是Throwable或其子类的实例。throw语句的一般形式一般的形式是:
thrownew异常类();new运算符被用来生成一个异常类的实例对象。例如:
thrownewArithmeticException();人为抛出异常的实例publicclassThrowDemo{publicstaticvoidmain(Stringargs[]){ intx=125; try{if(x%3!=0)thrownewArithmeticException();}catch(Exceptione){System.out.println(“捕获异常”+e.getMessage());
System.out.println(“不能被3整除”);
}System.out.println(“程序结束”);}}手动抛出异常如果整数不能被3整除,则抛出异常。importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in); try{age=sc.nextInt();System.out.println("年龄是"+age+"岁");
}catch(InputMismatchExceptione){System.out.println("输入的数据不匹配");
}System.out.println("程序结束");}}是否有其他异常?importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in);
try{age=sc.nextInt();
if(age<0) thrownewException();System.out.println("年龄是"+age+"岁");}
catch(InputMismatchExceptione){System.out.println("输入的数据不匹配");}
catch(Exceptione){System.out.println("输入的数据应该大于0");}System.out.println("程序结束");}}多重catch块一段代码可能会生成多个异常当引发异常时,按顺序查看每个catch语句,并执行第一个类型与异常类型匹配的语句。执行其中的一条catch语句之后,其他的catch语句将被忽略。try{…….}catch(ArrayIndexOutOfBoundsExceptione){……}catch(Exceptione){……}异常类的层次catch(ArrayIndexOutOfBoundsExceptione)catch(IndexOutOfBoundsExceptione)catch(RuntimeExceptione)catch(Exceptione)catch(Throwablee)算术异常类型强制转换异常空指针异常数组负下标异常数组下标越界异常下标越界异常多重catch块try{…...}catch(Exceptione){……}catch(ArrayIndexOutOfBoundsExceptione){……}
×使用多重catch语句时,异常子类一定要位于异常父类之前。importjava.util.*;classExample{publicstaticvoidmain(String[]args){intage;Scannersc=newScanner(System.in);
try{age=sc.nextInt();
if(age<0) thrownewException();System.out.println("年龄是"+age+"岁");}
catch(InputMismatchExceptione){System.out.println("输入的数据不匹配");}
catch(Exceptione){System.out.println("输入的数据应该大于0");}System.out.println("程序结束");}}练习classExceptionExample{publicstaticvoidmain(String[]args){ inta=8,b=2,c=0; try{ c=a/(b-2); System.out.println("计算结果:"+c); } catch(ArithmeticExceptionarithmeticException){ System.out.println("捕获了一个除零异常"); } catch(Exceptionexception){ System.out.println("捕获了一个异常"); }}}运行结果?下面程序可能有哪些异常?classTry2{publicstaticvoidmain(Stringargs[]){inti=0,a[]={5,6,7,8};for(i=0;i<=4;i++){System.out.print("a["+i+"]/"+i+"="+(a[i]/i));}System.out.println("结束!");
}}classTry2{publicstaticvoidmain(Stringargs[]){inti=0;inta[]={5,6,7,8};for(i=0;i<=4;i++){try{System.out.print("a["+i+"]/"+i+"="+(a[i]/i));}
catch(ArrayIndexOutOfBoundsExceptione){System.out.print("捕获数组下标越界异常!");}
catch(ArithmeticExceptione){System.out.print("捕获算术异常!");}
catch(Exceptione){System.out.print("捕获"+e.getMessage()+"异常!");}
finally{System.out.println("i="+i);}}System.out.println("结束!");}}捕获算术异常!i=0a[1]/1=6i=1a[2]/2=3i=2a[3]/3=2i=3捕获数组下标越界异常!i=4结束!finally块try、catch和finally块的执行流程finally子句可以保证,无论try块中是否抛出异常,finally块中的语句都会被执行到,这样可以对程序的状态作统一的管理。finally语句对增强程序的鲁棒性非常重要。try块finally块catch块无异常异常finally块示例classSystemException{publicstaticvoidmain(Stringargs[]){inta=68;intb=0;
try{System.out.println(a/b);//0用作了除数
}
catch(ArithmeticExceptione){System.out.println("0用作了除数");return;}finally{System.out.println("程序结束");}}}思考:如果没有finally语句,程序运行的结果有何不同?try-catch-finally应注意的问题每个try语句至少有一个catch语句对应,catch语句的排列顺序应该从特殊到一般。可以用一个catch语句处理多个异常类型,这时它的异常类型参数应该是多个异常类型的父类。try-cacth-finally语句中间不能插入其他语句异常处理机制
捕获异常声明抛出异常throwsTry-catch消极的处理方式积极的处理方式6.4声明异常处理异常处理异常可能会导致异常typecalledmethod(…)
throwsexception-list{//bodyofmethod}被调用的方法typecallingmethod(…){try{…
calledmethod(…);…}catch(Exceptione){…}}调用方法防止被调用的方法出现异常并处理异常
如果在一个方法中生成了异常,但是该方法并不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明异常。通常的情况是在该方法中并不确切知道该如何对这些异常进行处理,比如FileNotFoundException类异常,它由FileInputStream的构造方法产生,但在其构造方法中并不清楚如何处理它,是终止程序的执行还是新生成一个文件,这需要由调用它的方法来处理。声明异常
声明异常的方法:类型方法名([参数表])throws异常列表
声明异常说明该方法不对这些异常进行处理,抛弃它们。throws子句中可以同时指明多个异常。需要强调的是:对于非运行时异常,程序中必须要作处理,或者捕获,或者声明抛弃;而对于运行时异常,程序中则可不处理。importjava.io.*;publicclassaaa{publicstaticvoidmain(String[]args){inta;a=(int)System.in.read();System.out.println("a的值是"+a);}}实例throwsException实例classExceptionRaised{publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2){
intresult=operand1/operand2;returnresult;}publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();intresult=obj.calculate(9,0);System.out.println(result);}}解决方案一classExceptionRaised{publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2){intresult=0;try{ result=operand1/operand2;}catch(Exceptione){System.err.println("发生异常:"+e.toString());e.printStackTrace();}returnresult;}publicstaticvoidmain(String[]args){ExceptionRaisedobj=newExceptionRaised();intresult=obj.calculate(9,0);System.out.println(result);}}classExceptionRaised{publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2)throwsException{intresult=0;result=operand1/operand2; returnresult;}publicstaticvoidmain(String[]args){ ExceptionRaisedobj=newExceptionRaised();
try {intresult=obj.calculate(9,0); System.out.println(result); }
catch(Exceptione) {System.out.println("0不能做除数!"); }}}解决方案二解决方案三classExceptionRaised{publicExceptionRaised(){}publicintcalculate(intoperand1,intoperand2)throwsException{intresult=0;result=operand1/operand2; returnresult;
} publicstaticvoidmain(String[]args)throwsException{ ExceptionRaisedobj=newExceptionRaised(); intresult=obj.calculate(9,0); System.out.println(result); }}用throws声明抛弃异常在异常被抛出的过程中,任何方法都可以捕获异常并进行相应的处理。如果所有的方法都选择了抛出此异常,
最后JVM将捕获它,输出相关的错误信息,并终止程序的运行。publicmethod1(){intx;
try{x=System.in.read();
compute(x);}
catch(IOExceptionioe){System.out.println(“readerror”);}
catch(ArithmeticExceptione){System.out.println(“devidedby0”);}}publicintcompute(intx)throwsArithmeticException{intz=100/x;returnz;}method1compute异常异常抛出处理在方法内,可以是系统抛出异常,也可以用户自己抛出异常(throw)。方法中抛出异常对象,可以自己处理(try-catch-finally),也可以声明异常(throws)。调用方法可以处理被调用方法抛弃的异常,也可以继续声明异常。注意:一个方法被覆盖时,覆盖它的方法只能抛出相同的异常或异常的子类,即不能抛出新的异常。关于异常处理的说明练习fact方法的功能是求n!,阶乘值是byte类型。当n!的值超过byte数据类型的范围(Byte.MAX_VALUE)时,结果就会出错,但系统并不产生异常,所以要程序员自己产生异常。在主方法中调用该方法。要求用三种方式进行异常处理fact方法自己处理fact方法不处理,主方法处理fact方法和主方法都不处理6.5用户自定义异常类Java提供的内置异常不能满足程序需要怎么办?那就自定义异常吧!!自定义异常类必须继承自Throwable或Exception类,建议用Exception类。ThrowableErrorExceptionRuntimeException用户自定义异常类用户自定义异常类Exception异常类的构造方法方法说明Exception()
创建新异常Exception(Stringmessage)用字符串参数message描述异常信息并创建新异常。自定义异常类的形式:classMyException
extendsException{……}6.5自定义异常类用户自定义异常示例classMyExceptionextendsException{MyException(){ System.out.println("输入的数据中含有非数字字符");}}例:将输入的数字字符串转化为对应的整数,如果输入的字符串中含有非数字字符,则停止并显示错误提示信息。自定义异常类用
户
自
定
义
异
常
示
例classMyExceptionTest{
publicstaticvoidmain(Stringargs[]){
intnum; charc; StringBuffers=newStringBuffer();
try{
while((c=(char)System.in.read())!='\n'){ if(c>='0'&&c<='9'){s.append(c);} else{thrownewMyException();} } }
catch(MyExceptione)
{… }
catch(Exceptione)
{…}
finally
{num=Integer.parseInt(s.toString());}
System.out.println(num);}}用户自定义异常示例classMyExceptionextendsException{ publicMyException(Stringmessage) { super(message); }}用
户
自
定
义
异
常
示
例classTestMyException{
publicvoidregister(){Scannersc=newScanner(System.in);intnum;while(true){System.out.println("请输入登记的人数"); num=sc.nextInt();try{ if(num<0)
thrownewMyException("人数不能为负值"); else {System.out.println("登记的人数为:"+num);
System.exit(0); }}catch(MyExceptione){System.out.println(e.getMessage());}}}
publicstaticvoidmain(Stringargs[]){
TestMyExceptionmy=newTestMyException();my.register();}}
例:计算两个数之和,当任意一个数超出范围(10~20)时,抛出自己的异常。构造方法publicException();publicException(Strings);
可以接受字符串参数传入的信息,该信息通
常是对该异常所对应的错误的描述。publicclassNumRangeExceptionextendsException{publicNumRangeException(Stringmsg){super(msg);}publicclassNumRangeExceptionextendsExceptionpublicclassNumRangeExceptionextendsException{publicNumRangeException(Stringmsg){super(msg);}
publicstaticintCal(intn1,intn2){intanswer=-1;
try{if((n1<10)||(n1>20)||(n2<10)||(n2>20))
{NumRangeExceptione=newNumRangeException("Numbersnotwithinthespecifiedrange.");throwe;}elseanswer=n1+n2;}
catch(NumRangeExceptione){System.out.println(e.toString());}returnanswer;}}classExe{publicstaticvoidmain(Stringargs[]){intanswer; answer=NumRangeException.Cal(17,15);System.out.println(answer);answer=NumRangeException.Cal(17,25);System.out.println(answer);}}32NumRangeException:Numbersnotwithinthespecifiedrange.-1例:在定义银行类时,若取钱数大于余额则作为异
常处理(InsufficientFundsException)。思路:产生异常的条件是余额少于取额,因此是否抛出异常
要先判断该条件。确定产生异常的方法,应该在取钱方法(withdrawal)
中产生异常InsufficientFundsException。处理异常安排在调用withdrawal的时候,因此
withdrawal方法要声明异常,由上级方法捕获并处理。要定义好自己的异常。自定义异常类实例publicclassInsufficientFundsExceptionextendsException{privateBankexcepbank;privatedoubleexcepAmount;
InsufficientFundsException(Bankba,doubledAmount){excepbank=ba;excepAmount=dAmount;}publicStringexcepMesagge(){Stringstr=“Thebalance”+excepbank.getbalance()+“Thewithdrawalwas”+excepAmount;returnstr;}}classBank{doublebalance;//余额
publicvoiddeposite(doubledAmount)//存钱
{if(dAmount>0.0)balance+=dAmount;}
publicvoidwithdrawal(doubledAmount)throwsInsufficientFundsException{//取钱
if(balance<dAmout){thrownewInsufficientFundsException(this,dAmount);}balance=balance-dAmount;}
publicdoublegetbalance()//获取余额
{returnbalance;}}publicclassExceptionDemo{publicstaticvoidmain(Stringargs[]){try{Bankba=newBank();
ba.deposite(50);
ba.withdrawal(100);System.out.println(“Wi
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 第4课 喜看稻菽千重浪学案(1)高一上学期语文部编版必修上册
- 陕县2024年一级造价工程师《土建计量》考前冲刺试题含解析
- 黔东南南苗族侗族自治州黄平县2024年一级造价工程师《土建计量》统考试题含解析
- 【大学课件】管理信息系统
- 土木工程概预算课件
- 《财务管理流程介绍》课件
- 《不燃放烟花爆竹》课件
- 哈密无尘车间施工方案
- 有关九年级英语教学工作计划
- 合肥绿色环保围挡施工方案
- “教-学-评”一体化视域下高中英语课程目标实施研究
- 解码国家安全智慧树知到答案章节测试2023年国际关系学院
- 科研项目(课题)证明材料模板
- 2023简约黄蓝平安校园知识竞赛PPT模板
- JJF 1999-2022转子式流速仪校准规范
- GB/T 39204-2022信息安全技术关键信息基础设施安全保护要求
- JJG 736-1991气体层流流量传感器
- GB/T 6479-2013高压化肥设备用无缝钢管
- GB/T 17622-2008带电作业用绝缘手套
- 计量管理人员培训资料课件
- 英语天气课件
评论
0/150
提交评论