java异常io.docx
《java异常io.docx》由会员分享,可在线阅读,更多相关《java异常io.docx(17页珍藏版)》请在第壹文秘上搜索。
1、java异样io第卜章异样处理一、什么是异样:程序编译和运行时发生的错误称为异样。处理发生的异样称为异样处理。主要侧重于程序运行时发生的错误。异样处理的目的是保证程序的正常运行。一个异样就是一个异样类(对象)。案例一:packagecom.nkzy;importjava.util.Scanner:publicclassTestExceptionpublicstaticvoidmain(Stringargs)Scannerinput=newScanner(Systen).in);intnunl,nun2,resu111,result2;System,out.PrintIn(请输入第一个操作数:)
2、;numl=input,nextlntO;System,out.Println(请输入其次个操作数:);num2=input,nextlnt();result1=nunl/num2;System,out.println(numl/num2=+resultl);result2=nml*num2;System.out.printIn(numl*num2=+result2);当我们输入num2为。时,出现异样状况如卜丁当程序发生异样时,程序不能正常执行。异样处理:packagecom.nkzy;importjava.util.Scanner:publicClassTestExceptionpubli
3、cstaticvoidmain(Stringargs)Scannerinput=newScanner(System,in);intnuml,num2,result!,result2:System,out.PrintIn(请输入第一个操作数:);numl=input,nextlnt();System,out.PrintIn(请输入其次个操作数:);num2=input,nextIntO;tryresult1=numl/num2;System.out.pri11tln(11u11l/num2=+resultl);catch(ArithmeticExceptione)System,out.Print
4、In(发生异样);System.out.println(e.getMessage();result2=numl*num2;System,out.printIn(numl*num2=+result2);运行效果如下:当发生异样时,程序仍旧正常运行。二、异样的体系结构1、异样的类型Error类用于定义不希望程序能从其复原过来的灾难性故障。所以程序员不须要捕获它们。如:线程停止、虚拟机错误等。ObjectThrowableErrorThreadDeathAWTErroeExceptionSQI.ExccptionClassNotFountExccptionRuntimeException对于从Exc
5、eption派生出来的全部其他类,是我们重点学习的内容。运行时异样可以处理,也可以不处理;编译时异样必需进行处理。三、异样处理1、try/catch及try/catch/finallytry块:可能发生异样的代码。CatCh块:处理异样的代码,一个try后面可以跟多个CatCh,但是大类别的的异样必需在小类别异样的后面,同级别的没有依次。finalIy块:与try块一起运用,无论是否出现,finally块都将运行。案例:packagecom.nkzy:importjava.util.Scanner:publicclassTestExceptionpublicstaticvoidmain(Str
6、ingargs)ExceptionSQ1.ExceptionClassNotFoundExceptionRuntiineException编译时异样NUIIPOintEXCePIiOnNumberFormatExceptionTry块finallyfinallyCatch块没有异样异样intnuml,num2,result1,result2;numl10:num2=0;System,out.printIn(try块前代码);tryresult1=numl/num2;System.out.println(resultl);catch(Nu11PoiFiterExceptione)System.o
7、ut.Println(发生空指针异样);System,out.printIn(e.getMessageO);catch(ArithmeticExceptione)System.out.PrinIIn(发生数学异样);System,out.println(e.getMessage():catch(RuntimeExceptione)System.out.PrintJn(发生运行时异样):System,out.println(e.getMessage():finallySystem.out.PrintJn(打扫战场);System,out.printin(try-catch-finalIy块后代码
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- java 异常 io
