課件Java程序設計方案教程文件_第1頁
課件Java程序設計方案教程文件_第2頁
課件Java程序設計方案教程文件_第3頁
課件Java程序設計方案教程文件_第4頁
課件Java程序設計方案教程文件_第5頁
已閱讀5頁,還剩41頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Java程序設計JavaProgrammingSpring,20131成都信息工程學院計算機系ContentsWhyExceptions?WhatareExceptions?HandlingExceptionsCreatingExceptionTypes2chapter8ExceptionsWhyExceptions(異常)?Duringexecution(執行),programscanrunintomanykindsoferrors;Whatdowedowhenanerroroccurs?Javausesexceptionstoprovidetheerror-handlingcapabilitiesforitsprograms.3chapter8ExceptionsExceptions(異常)ErrorClassCritical(嚴重的)

errorwhichisnotacceptableinnormalapplicationprogram.

ExceptionClassPossibleexceptioninnormalapplicationprogramexecution;

Possibletohandlebyprogrammer.

4chapter8ExceptionsExceptions(異常)Treatexceptionasanobject.AllexceptionsareinstancesofaclassextendedfromThrowable

classoritssubclass.

Generally,aprogrammermakesnewexceptionclasstoextendtheExceptionclasswhichisasubclassofThrowableclass.6chapter8ExceptionsExceptionClass繼承關系ThrowableErrorExceptionRuntimeExceptionIOExceptionObject7異常類的層次結構:8Classifying(分類)JavaExceptionsUncheckedExceptions(非檢查性異常)Itisnotrequiredthatthesetypesofexceptionsbecaughtordeclaredonamethod.RuntimeexceptionscanbegeneratedbymethodsorbytheJVMitself.Errors

aregeneratedfromdeepwithintheJVM,andoftenindicateatrulyfatalstate.CheckedExceptions(檢查性異常)Musteitherbecaughtbyamethodordeclaredinitssignaturebyplacingexceptionsinthemethodsignature.9Exception的分類非檢查性異常(uncheckedexception):以RuntimeException為代表的一些類,編譯時發現不了,只在能運行時才能發現。檢查性異常(checkedexception):一般程序中可預知的問題,其產生的異常可能會帶來意想不到的結果,因此Java編譯器要求Java程序必須捕獲或聲明所有的非運行時異常。以IOException為代表的一些類。如果代碼中存在檢查性異常,必須進行異常處理,否則編譯不能通過。如:用戶連接數據庫SQLException、FileNotFoundException。10chapter8ExceptionsException的分類什么是RuntimeException:Java虛擬機在運行時生成的異常,如:被0除等系統錯誤、數組下標超范圍等,其產生比較頻繁,處理麻煩,對程序可讀性和運行效率影響太大。因此由系統檢測,用戶可不做處理,系統將它們交給默認的異常處理程序(當然,必要時,用戶可對其處理)。Java程序異常處理的原則是:對于Error和RuntimeException,可以在程序中進行捕獲和處理,但不是必須的。對于IOException及其他異常,必須在程序進行捕獲和處理。異常處理機制主要處理檢查性異常。11chapter8ExceptionsJavaExceptionTypeHierarchy(層次)virtualmachineerrors12系統異常類的層次結構:13chapter8ExceptionsException的分類System-DefinedException(系統定義的異常)Programmer-DefinedException(程序員自定義異常)14chapter8ExceptionsSystem-DefinedException

(系統定義的異常)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程序運行時發生異常,系統會拋出異常,如果程序中未處理和捕獲異常,異常拋出后程序運行中斷。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”);//不被執行}}系統給出的錯誤信息:Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:2atexception.Test.bar(Test.java:7)atexception.Test.main(Test.java:25)20HandlingExceptions(處理異常)Throwinganexception(拋出異常)Whenanerroroccurswithinamethod.Anexceptionobjectiscreatedandhandedofftotheruntimesystem(運行時系統).Theruntimesystemmustfindthecodetohandletheerror.Catchinganexception(捕獲異常)Theruntimesystem(運行時系統)searchesforcodetohandlethethrownexception.Itcanbeinthesamemethodorinsomemethodinthecall(調用)stack(堆棧).21chapter8ExceptionsKeywordsforJavaExceptionstry

Marksthestartofablockassociatedwithasetofexceptionhandlers.catch

Iftheblockenclosedbythetrygeneratesanexceptionofthistype,controlmoveshere;watchoutforimplicitsubsumption.finally

Alwayscalledwhenthetryblockconcludes,andafteranynecessarycatchhandleriscomplete.throws

Describestheexceptionswhichcanberaisedbyamethod.throw

Raisesanexceptiontothefirstavailablehandlerinthecallstack,unwindingthestackalongtheway.22拋出異常–throw,throws在一個方法的運行過程中,如果一個語句引起了錯誤時,含有這個語句的方法就會創建一個包含有關異常信息的異常對象,并將它傳遞給Java運行時系統。我們把生成異常對象并把它提交給運行時系統的過程稱為拋出(throw)異常。throw

—在方法體中用throw手工拋出異常;throws—在方法頭部間接拋出異常,即:申明方法中可能拋出的異常。231.在方法體中用throw手工拋出異常throw拋出異常,可以是系統定義的異常,也可以是用戶自定義的異常。語法格式:或例如:下面語句就拋出了一個IOException異常:thrownewIOException();異常類名對象名=new異常類構造函數;throw對象名;thrownew異常類構造函數;24throw

-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)

thrownewNullPointerException();

} catch(NullPointerExceptione){}}

publicstaticvoidmain(String[]args){inti=0;

ThrowStatement.exp(i);}}252.throws—間接拋出異常(申明異常)一個方法不處理它產生的異常,而是沿著調用層次向上傳遞,由調用它的方法來處理這些異常,叫聲明異常。在定義方法時用throws關鍵字將方法中可能產生的異常間接拋出。若一個方法可能引發一個異常,但它自己卻沒有處理,則應該聲明異常,并讓其調用者來處理這個異常,這時就需要用throws關鍵字來指明方法中可能引發的所有異常。類型方法名(參數列表)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);}}運行結果:

java.lang.NullPointerExceptionatThrowStatement.exp(ThrowStatement.java:4)atThrowStatement.main(ThrowStatement.java:8)28Exceptions-throwingmultiple(多個)

exceptionsAMethodcanthrowmultipleexceptions.Multipleexceptionsareseparatedbycommasafterthethrowskeyword:publicclassMyClass{ publicintcomputeFileSize()

throwsIOException,ArithmeticException { ...}}29HandlingExceptions在一個方法中,對于可能拋出的異常,處理方式有兩種:一個方法不處理它產生的異常,只在方法頭部聲明使用throws拋出異常,使異常沿著調用層次向上傳遞,由調用它的方法來處理這些異常。用try-catch-finally語句對異常及時處理;30HandlingExceptionspublicvoidreplaceValue(Stringname,Objectvalue)

throwsNoSuchAttributeException{Attrattr=find(name);if(attr==null)

thrownewNoSuchAttributeException(name);

attr.setValue(value);}try{…

replaceValue(“att1”,“newValue”);…}catch(NoSuchAttributeExceptione){e.printStackTrace();}當replaceValue(…)方法被調用時,調用者需處理異常。31處理異常語句try-catch-finally的基本格式為:try{ //可能產生異常的代碼;}//不能有其它語句分隔catch(異常類名異常對象名){ //異常處理代碼;//要處理的第一種異常}catch(異常類名異常對象名){ //異常處理代碼;//要處理的第二種異常}…finally{ //最終處理(缺省處理)}32Exceptions–Syntax(語法)示例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(可選項)mustbeassociatedwithatrystatementandidentifiesablockofstatementsthatareexecutedregardlessofwhetherornotanerroroccurswithinthetryblock.Evenifthetryandcatchblockhaveareturnstatementinthem,finallywillstillrun.35用try-catch-finally語句對異常及時處理-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)

thrownewNullPointerException(); } catch(NullPointerExceptione){}}

publicstaticvoidmain(String[]args){inti=0;

ThrowStatement.exp(i);}}36系統拋出異常后,捕獲異常,運行finally塊,程序運行繼續。publicclassTest{ publicvoidfoo(){

try{ inta[]=newint[2];

a[4]=1;/*causesaruntimeexceptionduetotheindex*/System.out.println(“Method:foo”);//若異常發生,不執行}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!!!”);

//繼續執行}}37運行結果: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);//不運行System.out.println("Value2="+val2);}}classThrowExample{publicstaticvoidmain(Stringargs[]){

UserTrialvalues=newUserTrial(-1,1);try{ values.show();}catch(IllegalValueExceptione){Syst

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論