課件Java程序設(shè)計(jì)方案_第1頁
課件Java程序設(shè)計(jì)方案_第2頁
課件Java程序設(shè)計(jì)方案_第3頁
課件Java程序設(shè)計(jì)方案_第4頁
課件Java程序設(shè)計(jì)方案_第5頁
已閱讀5頁,還剩42頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、chapter 8 exceptions2/47contentsnwhy exceptions?nwhat are exceptions?nhandling exceptionsncreating exception typeschapter 8 exceptions3/47why exceptions(異常異常)?nduring execution(執(zhí)行執(zhí)行), programs can run into many kinds of errors;nwhat do we do when an error occurs?java uses exceptions to provide the e

2、rror-handling capabilities for its programs.chapter 8 exceptions4/47exceptions (異常異常)1.error classcritical(嚴(yán)重的) error which is not acceptable in normal application program. 2.exception classpossible exception in normal application program execution; possible to handle by programmer. chapter 8 except

3、ions5/47exceptions (異常異常)nan exception is an event(事件事件) that occurs during the execution of a program that disrupts(使中斷使中斷) the normal flow(流程流程) of instructions(指令指令).chapter 8 exceptions6/47exceptions (異常異常)ntreat exception as an object .nall exceptions are instances of a class extended from thro

4、wable class or its subclass. ngenerally, a programmer makes new exception class to extend the exception class which is a subclass of throwable class.7exception class 繼承關(guān)系throwableerrorexceptionruntimeexceptionioexceptionobject8異常類的層次結(jié)構(gòu):異常類的層次結(jié)構(gòu):9classifying(分類分類) java exceptions1.unchecked exception

5、s(非檢查性異常非檢查性異常)it is not required that these types of exceptions be caught or declared on a method.runtime exceptions can be generated by methods or by the jvm itself.errors are generated from deep within the jvm, and often indicate a truly fatal state.2.checked exceptions(檢查性異常檢查性異常)must either be

6、caught by a method or declared in its signature by placing exceptions in the method signature.chapter 8 exceptions10/47exception的分類的分類n非檢查性異常非檢查性異常(unchecked exception):以runtimeexception為代表的一些類,編譯時(shí)發(fā)現(xiàn)不了,只在能運(yùn)行時(shí)才能發(fā)現(xiàn)。n檢查性異常檢查性異常(checked exception):一般程序中可預(yù)知的問題,其產(chǎn)生的異??赡軙硪庀氩坏降慕Y(jié)果,因此java編譯器要求java程序必須捕獲或聲明所

7、有的非運(yùn)行時(shí)異常。以ioexception為代表的一些類。如果代碼中存在檢查性異常,必須進(jìn)行異常處理,否則編譯不能通過。如:用戶連接數(shù)據(jù)庫sqlexception、filenotfoundexception。chapter 8 exceptions11/47exception的分類的分類n什么是什么是runtime exception:java虛擬機(jī)在運(yùn)行時(shí)生成的在運(yùn)行時(shí)生成的異常,如:被0除等系統(tǒng)錯誤、數(shù)組下標(biāo)超范圍等,其產(chǎn)生比較頻繁,處理麻煩,對程序可讀性和運(yùn)行效率影響太大。因此由系統(tǒng)檢測由系統(tǒng)檢測, 用戶可不用戶可不做處理做處理,系統(tǒng)將它們交給默認(rèn)的異常處理程序(當(dāng)然,必要時(shí),用戶可對其

8、處理)。njava程序異常處理的原則是:程序異常處理的原則是:1.對于error和runtimeexception,可以在程序中進(jìn)行捕獲和處理,但不是必須的。2.對于ioexception及其他異常及其他異常,必須在程序進(jìn)行捕獲和處必須在程序進(jìn)行捕獲和處理理。異常處理機(jī)制主要處理檢查性異常。12java exception type hierarchy(層次層次) virtual machine errorschapter 8 exceptions13/47系統(tǒng)異常類的層次結(jié)構(gòu):系統(tǒng)異常類的層次結(jié)構(gòu):chapter 8 exceptions14/47exception的分類的分類1.syste

9、m-defined exception(系統(tǒng)定義的異常系統(tǒng)定義的異常)2.programmer-defined exception(程序員自定程序員自定義異常義異常)chapter 8 exceptions15/47system-defined exception(系統(tǒng)定義的異常系統(tǒng)定義的異常)nraised implicitly by system because of illegal execution of program; ncreated by java system automatically; nexception extended from error class and ru

10、ntimeexception class. 16/47system-defined exceptionlindexoutofboundsexception: when beyond the bound of index in the object which use index, such as array, string, and vector larraystoreexception: when assign object of incorrect type to element of array lnegativearraysizeexception: when using a nega

11、tive size of array lnullpointerexception: when refer to object as a null pointerlsecurityexception: when violate security. caused by security managerlillegalmonitorstateexception: when the thread which is not owner of monitor involves wait or notify method chapter 8 exceptions17/47programmer-defined

12、 exception (程序員自定義異常程序員自定義異常)n exceptions raised by programmer subclass of exception class check by compiler whether the exception handler for exception occurred exists or notlif there is no handler, it is error. 18/47user-defined exceptions(用戶自定義異常用戶自定義異常)class usererr extends exception creating ex

13、ception types:chapter 8 exceptions19/47example 1:public class insufficientfundsexception extends exception private bankaccount excepbank; private double excepamount; insufficientfundsexception(bank ba, double damount) excepbank=ba; excepamount=damount; 20程序運(yùn)行時(shí)發(fā)生異常,系統(tǒng)會拋出異常,程序運(yùn)行時(shí)發(fā)生異常,系統(tǒng)會拋出異常,如果程序中未處理如

14、果程序中未處理和捕獲異常,異常拋出后程序運(yùn)行和捕獲異常,異常拋出后程序運(yùn)行中斷中斷。public class test public int bar() int a = new int2; for (int x = 0; x = 2; x+) ax = 0; /拋出異常,程序中斷拋出異常,程序中斷 return a; public static void main(string args) test t = new test(); t.bar();/程序中斷程序中斷 system.out.println(“method: foo”); /不被執(zhí)行不被執(zhí)行 系統(tǒng)給出的錯誤信息:系統(tǒng)給出的錯誤信息

15、:exception in thread main java.lang.arrayindexoutofboundsexception: 2at exception.test.bar(test.java:7)at exception.test.main(test.java:25)chapter 8 exceptions21/47handling exceptions(處理異常處理異常)1.throwing an exception(拋出異常拋出異常)when an error occurs within a method. lan exception object is created and

16、handed off to the runtime system(運(yùn)行時(shí)系統(tǒng)). the runtime system must find the code to handle the error. 2.catching an exception(捕獲異常捕獲異常)the runtime system(運(yùn)行時(shí)系統(tǒng)) searches for code to handle the thrown exception. it can be in the same method or in some method in the call(調(diào)用) stack(堆棧).22/47keywords for

17、java exceptionsltrymarks the start of a block associated with a set of exception handlers.lcatchif the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption.lfinallyalways called when the try block concludes, and after any necessary cat

18、ch handler is complete.lthrowsdescribes the exceptions which can be raised by a method.lthrowraises an exception to the first available handler in the call stack, unwinding the stack along the way.23/47拋出異常拋出異常 throw, throwsl在一個方法的運(yùn)行過程中,如果一個語句引起了錯誤時(shí),含有這個語句的方法就會創(chuàng)建一個包含有關(guān)異常信息的異常對象,并將它傳遞給java運(yùn)行時(shí)系統(tǒng)運(yùn)行時(shí)系統(tǒng)。

19、l我們把生成異常對象并把它提交給運(yùn)行時(shí)系統(tǒng)的過程稱為拋出拋出(throw)異常異常。1.throw 在在方法體方法體中用中用throw手工拋出異常;手工拋出異常;2.throws 在在方法頭部間接方法頭部間接拋出異常,即:申明拋出異常,即:申明方法中可能拋出的異常。方法中可能拋出的異常。24/471. 在方法體中用在方法體中用throw手工拋出異常手工拋出異常throw拋出異常,可以是系統(tǒng)定義的異常,也可以是用戶自系統(tǒng)定義的異常,也可以是用戶自定義的異常定義的異常。語法格式:或l例如:下面語句就拋出了一個ioexception異常:throw new ioexception();異常類名異常類

20、名 對象名對象名 new 異常類構(gòu)造函數(shù);異常類構(gòu)造函數(shù);throw 對象名;對象名;throw new 異常類構(gòu)造函數(shù)異常類構(gòu)造函數(shù);25/47throw exampleclass throwstatement extends exception public static void exp(int ptr) try if (ptr = 0) throw new nullpointerexception();catch(nullpointerexception e) public static void main(string args) int i = 0; throwstatement.

21、exp(i); 26/472. throws間接拋出異常(申明異常)l一個方法不處理它產(chǎn)生的異常一個方法不處理它產(chǎn)生的異常,而是沿著調(diào)用層次向上傳遞而是沿著調(diào)用層次向上傳遞,由由調(diào)用它的方法來處理這些異常調(diào)用它的方法來處理這些異常,叫叫聲明異常聲明異常。l在在定義方法時(shí)定義方法時(shí)用用throws關(guān)鍵字將方法中可能產(chǎn)生的異常間接拋關(guān)鍵字將方法中可能產(chǎn)生的異常間接拋出。出。l若一個方法可能引發(fā)一個異常,但它自己卻沒有處理,則應(yīng)該若一個方法可能引發(fā)一個異常,但它自己卻沒有處理,則應(yīng)該聲明聲明異常,并讓其調(diào)用者來處理這個異常,這時(shí)就需要用異常,并讓其調(diào)用者來處理這個異常,這時(shí)就需要用throws關(guān)鍵字

22、來指明方法中可能引發(fā)的所有異常關(guān)鍵字來指明方法中可能引發(fā)的所有異常。類型類型 方法名方法名(參數(shù)列表參數(shù)列表) throws 異常列表異常列表 /代碼代碼 27example 1:public class exceptiontest void proc(int sel) throws arrayindexoutofboundsexception system.out.println(“in situation + sel ); if(sel=1) int iarray =new int4; iarray10=3; /拋出異常拋出異常 28/47異常向上傳遞exampleclass throws

23、tatement extends exception public static void exp(int ptr) throws nullpointerexception if (ptr = 0) throw new nullpointerexception(); public static void main(string args) int i = 0; throwstatement.exp(i); 運(yùn)行結(jié)果: java.lang.nullpointerexception at throwstatement.exp(throwstatement.java:4) at throwstate

24、ment.main(throwstatement.java:8)29exceptions - throwing multiple(多個多個) exceptionsa method can throw multiple exceptions. multiple exceptions are separated by commas after the throws keyword:public class myclass public int computefilesize() throws ioexception, arithmeticexception. 30/47handling excep

25、tionsl在一個方法中,對于可能拋出的異常,處理方式在一個方法中,對于可能拋出的異常,處理方式有兩種:有兩種:1.一個方法不處理它產(chǎn)生的異常一個方法不處理它產(chǎn)生的異常,只在方法頭部聲明只在方法頭部聲明使用使用throws拋出異常,使異常沿著調(diào)用層次向上拋出異常,使異常沿著調(diào)用層次向上傳遞傳遞,由調(diào)用它的方法來處理這些異常。由調(diào)用它的方法來處理這些異常。2.用用try-catch-finally語句對異常及時(shí)處理;語句對異常及時(shí)處理;31handling exceptionspublic void replacevalue(string name, object value) throws n

26、osuchattributeexception attr attr=find(name); if(attr=null) throw new nosuchattributeexception(name); attr.setvalue(value);try replacevalue(“att1”, “newvalue”); catch(nosuchattributeexception e) e.printstacktrace();當(dāng)replacevalue()方法被調(diào)用時(shí),調(diào)用者方法被調(diào)用時(shí),調(diào)用者需處理異常。需處理異常。32處理異常語句處理異常語句try-catch-finally的基本格式為:

27、的基本格式為:try /可能產(chǎn)生異常的代碼;可能產(chǎn)生異常的代碼; /不能有其它語句分隔不能有其它語句分隔catch(異常類名異常類名 異常對象名異常對象名) / 異常處理代碼;異常處理代碼; /要處理的第一種異常要處理的第一種異常catch(異常類名異常類名 異常對象名異常對象名) /異常處理代碼;異常處理代碼; /要處理的第二種異常要處理的第二種異常finally /最終處理(缺省處理)最終處理(缺省處理)33exceptions syntax(語法語法)示例示例try / code which might throw an exception/ . catch(filenotfoundex

28、ception x) / code to handle a filenotfound exception catch(ioexception x) / code to handle any other i/o exceptions catch(exception x) / code to catch any other type of exception finally / this code is always executed whether an exception was thrown/ or not. a good place to put clean-up code. ie. cl

29、ose/ any open files, etc.34handling exceptions(處理異常)try-catch 或或 try-catch-finally .three statements help define how exceptions are handled:1. try identifies a block of statements within which an exception might be thrown; a try statement can have multiple catch statements associated with it.2. catc

30、h must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. the statements are executed if an exception of a particular type occurs within the try block. 35handling exceptions3. finally (可選項(xiàng)) must be associated with a try statement a

31、nd identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. even if the try and catch block have a return statement in them, finally will still run.36用用try-catch-finally語句對異常及時(shí)處理語句對異常及時(shí)處理exampleclass throwstatement extends exception public

32、 static void exp(int ptr) try if (ptr = 0) throw new nullpointerexception();catch(nullpointerexception e) public static void main(string args) int i = 0; throwstatement.exp(i); 37系統(tǒng)拋出異常后,捕獲異常,運(yùn)行系統(tǒng)拋出異常后,捕獲異常,運(yùn)行finally塊,程序運(yùn)行繼續(xù)。塊,程序運(yùn)行繼續(xù)。public class test public void foo() try int a = new int2; a4 = 1;

33、/* causes a runtime exception due to the index */ system.out.println(“method: foo”);/若異常發(fā)生,不執(zhí)行若異常發(fā)生,不執(zhí)行 catch (arrayindexoutofboundsexception e) system.out.println(exception: + e.getmessage(); e.printstacktrace(); finally system.out.println(finally block always execute!); public static void main(str

34、ing args) test t = new test(); t.foo(); system.out.println(“excecution after exception!”); /繼續(xù)執(zhí)行繼續(xù)執(zhí)行 38運(yùn)行結(jié)果:exception: 4java.lang.arrayindexoutofboundsexception: 4at exception.test.foo(test.java:8)at exception.test.main(test.java:20)finally block always execute!excecution after exception!39exception

35、s -throwing multiple exceptionspublic void method1() myclass anobject = new myclass();try int thesize = anoputefilesize(); catch(arithmeticexception x) / . catch(ioexception x) / . 40exceptions -catching multiple exceptionseach try block can catch multiple exceptions.start with the most specific exc

36、eptionsfilenotfoundexception is a subclass of io exceptionit must appear before ioexception in the catch listpublic void method1() fileinputstream afile; try afile = new fileinputstream(.);int achar = afile.read();/. catch(filenotfoundexception x) / . catch(ioexception x) / . 41exception -the catch-

37、all handlersince all exception classes are a subclass of the exception class, a catch handler which catches exception will catch all exceptions.it must be the last in the catch list.public void method1()fileinputstream afile;try afile = new fileinputstream(.);int achar = afile.read();/.catch(ioexcep

38、tion x)/ .catch(exception x)/ catch all exceptions 42user-defined exceptions(用戶自定義異常用戶自定義異常)的處理的處理class usererr extends exception 用戶自定義異常用戶自定義異常是檢查性異常是檢查性異常(checked exception),必須用必須用throw手工拋出并處理。手工拋出并處理。class userclass usererr x = new usererr(); . if (val 1) throw x;43/throwexample.javaclass illegal

39、valueexception extends exception class usertrial int val1,val2; public usertrial(int a,int b) val1=a; val2=b; void show() throws illegalvalueexception if (val10) throw new illegalvalueexception(); system.out.println(“value1=”+ val1);/不運(yùn)行 system.out.println(value2 =+val2); class throwexample public static void main(string args ) usertrial values=new usertrial(-1,1); try values.show(); c

溫馨提示

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

最新文檔

評論

0/150

提交評論