预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共24页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

第六讲异常处理异常的概念异常的抛出和捕获异常的抛出和捕获示意图三种异常类型Java语言中的部分异常类异常代码的处理try-catch-finally异常匹配顺序//Note:该文件无法通过编译 importjava.io.*; importjava.util.List; importjava.util.ArrayList; publicclassListOfNumbers{ privateList<Integer>list; privatestaticfinalintSIZE=10; publicListOfNumbers(){ list=newArrayList<Integer>(SIZE); for(inti=0;i<SIZE;i++){ list.add(newInteger(i)); } } publicvoidwriteList(){ PrintWriterout=newPrintWriter(newFileWriter("OutFile.txt")); for(inti=0;i<SIZE;i++){ out.println("Valueat:"+i+"="+list.get(i)); } out.close();} } }importjava.io.*; importjava.util.List; importjava.util.ArrayList; publicclassListOfNumbers{ privateList<Integer>list; privatestaticfinalintSIZE=10; publicListOfNumbers(){ list=newArrayList<Integer>(SIZE); for(inti=0;i<SIZE;i++){ list.add(newInteger(i)); } } publicvoidwriteList(){ try{ PrintWriterout=newPrintWriter(newFileWriter("OutFile.txt")); for(inti=0;i<SIZE;i++){ out.println("Valueat:"+i+"="+list.get(i)); } } catch(IOExceptionexp){ System.out.println(“CaughtIOException:“+exp.getMessage()); } finally{ if(out!=null){ System.out.println("ClosingPrintWriter"); out.close(); } else{ System.out.println("PrintWriternotopen"); } } } }异常声明抛出异常抛出异常语句importjava.util.*; classExceptionOneextendsException{} classExceptionTwoextendsException{} classExceptionThreeextendsExceptionOne{} classExceptionFourextendsExceptionTwo{} classBaseClass{ publicvoidf()throwsExceptionOne{thrownewExceptionOne();} } publicclassDerivedClassextendsBaseClass{ publicvoidf()throwsExceptionOne,ExceptionTwo{//编译错误,不能抛出父类方法未声明的异常 Randomrand=newRandom(); if(rand.nextInt(15)>5) thrownewExceptionOne(); else thrownewExceptionTwo(); } publicstaticvoidmain(String[]args){ DerivedClassd=newDerivedClass(); try{ d.f(); } catch(ExceptionOneone){ } catch(ExceptionTwotwo){ } } }importjava.util.*; classExceptionOneextendsException{} classExceptionTwoextendsException{} classExceptionThreeextendsExceptionOne{} classExceptionFourextendsExceptionTwo{} classBaseClass{ publicvoidf()throwsExceptionOne{