




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Java程序設(shè)計(jì)JavaProgrammingSpring,20131成都信息工程學(xué)院計(jì)算機(jī)系ContentsWhyExceptions?WhatareExceptions?HandlingExceptionsCreatingExceptionTypes2chapter8ExceptionsWhyExceptions(異常)?Duringexecution(執(zhí)行),programscanrunintomanykindsoferrors;Whatdowedowhenanerroroccurs?Javausesexceptionstoprovidetheerror-handlingcapabilitiesforitsprograms.3chapter8ExceptionsExceptions(異常)ErrorClassCritical(嚴(yán)重的)
errorwhichisnotacceptableinnormalapplicationprogram.
ExceptionClassPossibleexceptioninnormalapplicationprogramexecution;
Possibletohandlebyprogrammer.
4chapter8ExceptionsExceptions(異常)Treatexceptionasanobject.AllexceptionsareinstancesofaclassextendedfromThrowable
classoritssubclass.
Generally,aprogrammermakesnewexceptionclasstoextendtheExceptionclasswhichisasubclassofThrowableclass.6chapter8ExceptionsExceptionClass繼承關(guān)系ThrowableErrorExceptionRuntimeExceptionIOExceptionObject7異常類的層次結(jié)構(gòu):8Classifying(分類)JavaExceptionsUncheckedExceptions(非檢查性異常)Itisnotrequiredthatthesetypesofexceptionsbecaughtordeclaredonamethod.RuntimeexceptionscanbegeneratedbymethodsorbytheJVMitself.Errors
aregeneratedfromdeepwithintheJVM,andoftenindicateatrulyfatalstate.CheckedExceptions(檢查性異常)Musteitherbecaughtbyamethodordeclaredinitssignaturebyplacingexceptionsinthemethodsignature.9Exception的分類非檢查性異常(uncheckedexception):以RuntimeException為代表的一些類,編譯時(shí)發(fā)現(xiàn)不了,只在能運(yùn)行時(shí)才能發(fā)現(xiàn)。檢查性異常(checkedexception):一般程序中可預(yù)知的問(wèn)題,其產(chǎn)生的異??赡軙?huì)帶來(lái)意想不到的結(jié)果,因此Java編譯器要求Java程序必須捕獲或聲明所有的非運(yùn)行時(shí)異常。以IOException為代表的一些類。如果代碼中存在檢查性異常,必須進(jìn)行異常處理,否則編譯不能通過(guò)。如:用戶連接數(shù)據(jù)庫(kù)SQLException、FileNotFoundException。10chapter8ExceptionsException的分類什么是RuntimeException:Java虛擬機(jī)在運(yùn)行時(shí)生成的異常,如:被0除等系統(tǒng)錯(cuò)誤、數(shù)組下標(biāo)超范圍等,其產(chǎn)生比較頻繁,處理麻煩,對(duì)程序可讀性和運(yùn)行效率影響太大。因此由系統(tǒng)檢測(cè),用戶可不做處理,系統(tǒng)將它們交給默認(rèn)的異常處理程序(當(dāng)然,必要時(shí),用戶可對(duì)其處理)。Java程序異常處理的原則是:對(duì)于Error和RuntimeException,可以在程序中進(jìn)行捕獲和處理,但不是必須的。對(duì)于IOException及其他異常,必須在程序進(jìn)行捕獲和處理。異常處理機(jī)制主要處理檢查性異常。11chapter8ExceptionsJavaExceptionTypeHierarchy(層次)virtualmachineerrors12系統(tǒng)異常類的層次結(jié)構(gòu):13chapter8ExceptionsException的分類System-DefinedException(系統(tǒng)定義的異常)Programmer-DefinedException(程序員自定義異常)14chapter8ExceptionsSystem-DefinedException
(系統(tǒng)定義的異常)Raisedimplicitlybysystembecauseofillegalexecutionofprogram;CreatedbyJavaSystemautomatically;ExceptionextendedfromErrorclassandRuntimeExceptionclass.
15chapter8ExceptionsSystem-DefinedExceptionIndexOutOfBoundsException:Whenbeyondtheboundofindexintheobjectwhichuseindex,suchasarray,string,andvectorArrayStoreException:WhenassignobjectofincorrecttypetoelementofarrayNegativeArraySizeException:
WhenusinganegativesizeofarrayNullPointerException:WhenrefertoobjectasanullpointerSecurityException:Whenviolatesecurity.CausedbysecuritymanagerIllegalMonitorStateException:Whenthethreadwhichisnotownerofmonitorinvolveswaitornotifymethod16Programmer-DefinedException
(程序員自定義異常)
Exceptionsraisedbyprogrammer
SubclassofException
classCheckbycompilerwhethertheexceptionhandlerforexceptionoccurredexistsornotIfthereisnohandler,itiserror.
17chapter8ExceptionsUser-definedExceptions
(用戶自定義異常)classUserErrextendsException
{ …}CreatingExceptionTypes:18Example1:publicclassInsufficientFundsException
extendsException
{ privateBankAccountexcepbank;privatedoubleexcepAmount;
InsufficientFundsException(Bankba,doubledAmount) { excepbank=ba;excepAmount=dAmount; }}19chapter8Exceptions程序運(yùn)行時(shí)發(fā)生異常,系統(tǒng)會(huì)拋出異常,如果程序中未處理和捕獲異常,異常拋出后程序運(yùn)行中斷。publicclassTest{publicint[]bar(){ inta[]=newint[2]; for(intx=0;x<=2;x++){
a[x]=0;//拋出異常,程序中斷} returna;}publicstaticvoidmain(String[]args){ Testt=newTest(); t.bar(); //程序中斷 System.out.println(“Method:foo”);//不被執(zhí)行}}系統(tǒng)給出的錯(cuò)誤信息:Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:2atexception.Test.bar(Test.java:7)atexception.Test.main(Test.java:25)20HandlingExceptions(處理異常)Throwinganexception(拋出異常)Whenanerroroccurswithinamethod.Anexceptionobjectiscreatedandhandedofftotheruntimesystem(運(yùn)行時(shí)系統(tǒng)).Theruntimesystemmustfindthecodetohandletheerror.Catchinganexception(捕獲異常)Theruntimesystem(運(yùn)行時(shí)系統(tǒng))searchesforcodetohandlethethrownexception.Itcanbeinthesamemethodorinsomemethodinthecall(調(diào)用)stack(堆棧).21chapter8ExceptionsKeywordsforJavaExceptionstry
Marksthestartofablockassociatedwithasetofexceptionhandlers.catch
Iftheblockenclosedbythetrygeneratesanexceptionofthistype,controlmoveshere;watchoutforimplicitsubsumption.finally
Alwayscalledwhenthetryblockconcludes,andafteranynecessarycatchhandleriscomplete.throws
Describestheexceptionswhichcanberaisedbyamethod.throw
Raisesanexceptiontothefirstavailablehandlerinthecallstack,unwindingthestackalongtheway.22拋出異常–throw,throws在一個(gè)方法的運(yùn)行過(guò)程中,如果一個(gè)語(yǔ)句引起了錯(cuò)誤時(shí),含有這個(gè)語(yǔ)句的方法就會(huì)創(chuàng)建一個(gè)包含有關(guān)異常信息的異常對(duì)象,并將它傳遞給Java運(yùn)行時(shí)系統(tǒng)。我們把生成異常對(duì)象并把它提交給運(yùn)行時(shí)系統(tǒng)的過(guò)程稱為拋出(throw)異常。throw
—在方法體中用throw手工拋出異常;throws—在方法頭部間接拋出異常,即:申明方法中可能拋出的異常。231.在方法體中用throw手工拋出異常throw拋出異常,可以是系統(tǒng)定義的異常,也可以是用戶自定義的異常。語(yǔ)法格式:或例如:下面語(yǔ)句就拋出了一個(gè)IOException異常:thrownewIOException();異常類名對(duì)象名=new異常類構(gòu)造函數(shù);throw對(duì)象名;thrownew異常類構(gòu)造函數(shù);24throw
-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)
thrownewNullPointerException();
} catch(NullPointerExceptione){}}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}252.throws—間接拋出異常(申明異常)一個(gè)方法不處理它產(chǎn)生的異常,而是沿著調(diào)用層次向上傳遞,由調(diào)用它的方法來(lái)處理這些異常,叫聲明異常。在定義方法時(shí)用throws關(guān)鍵字將方法中可能產(chǎn)生的異常間接拋出。若一個(gè)方法可能引發(fā)一個(gè)異常,但它自己卻沒(méi)有處理,則應(yīng)該聲明異常,并讓其調(diào)用者來(lái)處理這個(gè)異常,這時(shí)就需要用throws關(guān)鍵字來(lái)指明方法中可能引發(fā)的所有異常。類型方法名(參數(shù)列表)throws
異常列表{ //…代碼}26Example1:publicclassExceptionTest{ voidProc(intsel)throwsArrayIndexOutOfBoundsException{
System.out.println(“InSituation"+sel); if(sel==1){ intiArray[]=newint[4];iArray[10]=3;//拋出異常 }
}
}27異常向上傳遞-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr)throws
NullPointerException{if(ptr==0)
thrownewNullPointerException();}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}運(yùn)行結(jié)果:
java.lang.NullPointerExceptionatThrowStatement.exp(ThrowStatement.java:4)atThrowStatement.main(ThrowStatement.java:8)28Exceptions-throwingmultiple(多個(gè))
exceptionsAMethodcanthrowmultipleexceptions.Multipleexceptionsareseparatedbycommasafterthethrowskeyword:publicclassMyClass{ publicintcomputeFileSize()
throwsIOException,ArithmeticException { ...}}29HandlingExceptions在一個(gè)方法中,對(duì)于可能拋出的異常,處理方式有兩種:一個(gè)方法不處理它產(chǎn)生的異常,只在方法頭部聲明使用throws拋出異常,使異常沿著調(diào)用層次向上傳遞,由調(diào)用它的方法來(lái)處理這些異常。用try-catch-finally語(yǔ)句對(duì)異常及時(shí)處理;30HandlingExceptionspublicvoidreplaceValue(Stringname,Objectvalue)
throwsNoSuchAttributeException{Attrattr=find(name);if(attr==null)
thrownewNoSuchAttributeException(name);
attr.setValue(value);}try{…
replaceValue(“att1”,“newValue”);…}catch(NoSuchAttributeExceptione){e.printStackTrace();}當(dāng)replaceValue(…)方法被調(diào)用時(shí),調(diào)用者需處理異常。31處理異常語(yǔ)句try-catch-finally的基本格式為:try{ //可能產(chǎn)生異常的代碼;}//不能有其它語(yǔ)句分隔catch(異常類名異常對(duì)象名){ //異常處理代碼;//要處理的第一種異常}catch(異常類名異常對(duì)象名){ //異常處理代碼;//要處理的第二種異常}…finally{ //最終處理(缺省處理)}32Exceptions–Syntax(語(yǔ)法)示例try{
//Codewhichmightthrowanexception //...}catch(FileNotFoundExceptionx){
//codetohandleaFileNotFoundexception}catch(IOExceptionx){
//codetohandleanyotherI/Oexceptions}catch(Exceptionx){
//Codetocatchanyothertypeofexception}finally{
//ThiscodeisALWAYSexecutedwhetheranexceptionwasthrown //ornot.Agoodplacetoputclean-upcode.ie.close //anyopenfiles,etc...}33HandlingExceptions(處理異常)try-catch或try-catch-finally.Threestatementshelpdefinehowexceptionsarehandled:tryidentifiesablockofstatementswithinwhichanexceptionmightbethrown;Atrystatementcanhavemultiplecatchstatementsassociatedwithit.catchmustbeassociatedwithatrystatementandidentifiesablockofstatementsthatcanhandleaparticulartypeofexception.Thestatementsareexecutedifanexceptionofaparticulartypeoccurswithinthetryblock.34HandlingExceptionsfinally(可選項(xiàng))mustbeassociatedwithatrystatementandidentifiesablockofstatementsthatareexecutedregardlessofwhetherornotanerroroccurswithinthetryblock.Evenifthetryandcatchblockhaveareturnstatementinthem,finallywillstillrun.35用try-catch-finally語(yǔ)句對(duì)異常及時(shí)處理-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)
thrownewNullPointerException(); } catch(NullPointerExceptione){}}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}36系統(tǒng)拋出異常后,捕獲異常,運(yùn)行finally塊,程序運(yùn)行繼續(xù)。publicclassTest{ publicvoidfoo(){
try{ inta[]=newint[2];
a[4]=1;/*causesaruntimeexceptionduetotheindex*/System.out.println(“Method:foo”);//若異常發(fā)生,不執(zhí)行}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("exception:"+e.getMessage()); e.printStackTrace();}finally{System.out.println("Finallyblockalwaysexecute!!!");}}publicstaticvoidmain(String[]args){Testt=newTest();t.foo();
System.out.println(“ExcecutionafterException!!!”);
//繼續(xù)執(zhí)行}}37運(yùn)行結(jié)果:exception:4java.lang.ArrayIndexOutOfBoundsException:4 atexception.Test.foo(Test.java:8) atexception.Test.main(Test.java:20)Finallyblockalwaysexecute!!!ExcecutionafterException!!!38Exceptions-throwingmultipleexceptionspublicvoidmethod1(){ MyClassanObject=newMyClass(); try{ inttheSize=anOputeFileSize(); }catch(ArithmeticExceptionx){ //... }catch(IOExceptionx){ //...}}39Exceptions-catchingmultipleexceptionsEachtryblockcancatchmultipleexceptions.StartwiththemostspecificexceptionsFileNotFoundExceptionisasubclassofIOExceptionItMUSTappearbeforeIOException
inthecatchlistpublicvoidmethod1(){ FileInputStreamaFile; try{ aFile=newFileInputStream(...); intaChar=aFile.read(); //... }catch(FileNotFoundExceptionx){ //... }catch(IOExceptionx){ //...}}40Exception-Thecatch-allHandlerSinceallExceptionclassesareasubclassoftheExceptionclass,acatchhandlerwhichcatches"Exception"willcatchallexceptions.ItmustbethelastinthecatchList.publicvoidmethod1(){ FileInputStreamaFile; try{ aFile=newFileInputStream(...); intaChar=aFile.read(); //... } catch(IOExceptionx){ //... } catch(Exceptionx){ //CatchAllExceptions}}41User-definedExceptions(用戶自定義異常)的處理classUserErrextendsException{ …}用戶自定義異常是檢查性異常(checkedexception),必須用throw手工拋出并處理。classUserClass{ …
UserErr
x=newUserErr();...if(val<1)
throw
x;}42//ThrowExample.javaclassIllegalValueException extendsException{}
classUserTrial{intval1,val2;publicUserTrial(inta,intb){val1=a;val2=b;}voidshow()throwsIllegalValueException{
if((val1<0)||(val2>0)) thrownewIllegalValueException();System.out.println(“Value1=”+val1);//不運(yùn)行System.out.println("Value2="+val2);}}classThrowExample{publicstaticvoidmain(Stringargs[]){
UserTrialvalues=newUserTrial(-1,1);try{ values.show();}catch(IllegalValueExceptione){Syst
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年中國(guó)普及型彩色攝像機(jī)市場(chǎng)調(diào)查研究報(bào)告
- 2025屆四川省成都市蓉城名校聯(lián)考高三上學(xué)期開(kāi)學(xué)考-物理試題(含答案)
- 2025年中國(guó)新量子亞健康檢測(cè)儀市場(chǎng)調(diào)查研究報(bào)告
- 2025年中國(guó)數(shù)字鏈路復(fù)接器數(shù)據(jù)監(jiān)測(cè)報(bào)告
- 小兒假膜性腸炎護(hù)理
- 2025-2030年中國(guó)三級(jí)綜合醫(yī)院行業(yè)發(fā)展前景調(diào)研及投資規(guī)劃報(bào)告
- 肇慶市實(shí)驗(yàn)中學(xué)高中生物三:2免疫調(diào)節(jié)導(dǎo)學(xué)案(第課時(shí))
- 新疆科信職業(yè)技術(shù)學(xué)院《體育基礎(chǔ)》2023-2024學(xué)年第二學(xué)期期末試卷
- 新疆莎車縣2025屆初三第一次摸底考試英語(yǔ)試題試卷含答案
- 新鄉(xiāng)市紅旗區(qū)2025年數(shù)學(xué)三下期末監(jiān)測(cè)模擬試題含解析
- 《尼爾斯騎鵝旅行記》讀書分享課件
- 邏輯學(xué)導(dǎo)論 第4章 謬誤
- 第六章學(xué)習(xí)法治思想提升法治素養(yǎng)講解
- 無(wú)錫地鐵線網(wǎng)文旅融合一體化發(fā)展策略研究
- 8S管理介紹課件
- 押運(yùn)員管理考核規(guī)定(4篇)
- 夜市現(xiàn)場(chǎng)管理制度內(nèi)容
- 醫(yī)療診斷中的批判性思維應(yīng)用
- 健康管理考試題庫(kù)及答案
- 高三臨界生會(huì)議課件
- 安徽省2024年中考道德與法治真題試卷(含答案)
評(píng)論
0/150
提交評(píng)論