




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、ContentsnWhy Exceptions?nWhat are Exceptions?nHandling ExceptionsnCreating Exception TypesWhy Exceptions(異常異常)?nDuring execution(執(zhí)行執(zhí)行), programs can run into many kinds of errors;nWhat do we do when an error occurs?nJava uses exceptions to provide the error-handling capabilities for its programs.Exc
2、eptions (異常異常)nError ClassnCritical(嚴(yán)重的嚴(yán)重的) error which is not acceptable in normal application program. nException ClassnPossible exception in normal application program execution; nPossible to handle by programmer. Exceptions (異常異常)nAn exception is an event(事件事件) that occurs during the execution o
3、f a program that disrupts(使中斷使中斷) the normal flow(流程流程) of instructions(指令指令).Exceptions (異常異常)nTreat exception as an object .nAll exceptions are instances of a class extended from Throwable class or its subclass. nGenerally, a programmer makes new exception class to extend the Exception class which
4、 is a subclass of Throwable class.Exception Class 承繼關(guān)系ThrowableErrorExceptionRuntimeExceptionIOExceptionObject異常類的層次構(gòu)造:異常類的層次構(gòu)造:Classifying(分類分類) Java ExceptionsUnchecked Exceptions(非檢查性異常非檢查性異常)It is not required that these types of exceptions be caught or declared on a method.Runtime exceptions ca
5、n be generated by methods or by the JVM itself.Errors are generated from deep within the JVM, and often indicate a truly fatal state.Checked Exceptions(檢查性異常檢查性異常)Must either be caught by a method or declared in its signature by placing exceptions in the method signature.Exception的分類的分類n非檢查性異常非檢查性異常
6、(unchecked exception):n以以RuntimeException為代表的一些類,編譯時(shí)發(fā)為代表的一些類,編譯時(shí)發(fā)現(xiàn)不了,只在能運(yùn)轉(zhuǎn)時(shí)才干發(fā)現(xiàn)?,F(xiàn)不了,只在能運(yùn)轉(zhuǎn)時(shí)才干發(fā)現(xiàn)。n檢查性異常檢查性異常(checked exception):n普通程序中可預(yù)知的問題,其產(chǎn)生的異常能夠會(huì)帶來普通程序中可預(yù)知的問題,其產(chǎn)生的異常能夠會(huì)帶來意想不到的結(jié)果,因此意想不到的結(jié)果,因此Java編譯器要求編譯器要求Java程序必程序必需捕獲或聲明一切的非運(yùn)轉(zhuǎn)時(shí)異常。需捕獲或聲明一切的非運(yùn)轉(zhuǎn)時(shí)異常。n以以IOException為代表的一些類。假設(shè)代碼中存在為代表的一些類。假設(shè)代碼中存在檢查性異常,必
7、需進(jìn)展異常處置,否那么編譯不能經(jīng)檢查性異常,必需進(jìn)展異常處置,否那么編譯不能經(jīng)過。如:用戶銜接數(shù)據(jù)庫過。如:用戶銜接數(shù)據(jù)庫SQLException、FileNotFoundException。Exception的分類的分類n什么是什么是Runtime Exception:nJava虛擬機(jī)在運(yùn)轉(zhuǎn)時(shí)生成的異常,如:被虛擬機(jī)在運(yùn)轉(zhuǎn)時(shí)生成的異常,如:被0除除等系統(tǒng)錯(cuò)誤、數(shù)組下標(biāo)超范圍等,其產(chǎn)生比較等系統(tǒng)錯(cuò)誤、數(shù)組下標(biāo)超范圍等,其產(chǎn)生比較頻繁,處置費(fèi)事,對(duì)程序可讀性和運(yùn)轉(zhuǎn)效率影頻繁,處置費(fèi)事,對(duì)程序可讀性和運(yùn)轉(zhuǎn)效率影響太大。因此由系統(tǒng)檢測(cè)響太大。因此由系統(tǒng)檢測(cè), 用戶可不做處置,用戶可不做處置,系統(tǒng)將它
8、們交給默許的異常處置程序系統(tǒng)將它們交給默許的異常處置程序(當(dāng)然,當(dāng)然,必要時(shí),用戶可對(duì)其處置必要時(shí),用戶可對(duì)其處置)。nJava程序異常處置的原那么是:程序異常處置的原那么是:n對(duì)于對(duì)于Error和和RuntimeException,可以在程,可以在程序中進(jìn)展捕獲和處置,但不是必需的。序中進(jìn)展捕獲和處置,但不是必需的。n對(duì)于對(duì)于IOException及其他異常,必需在程序及其他異常,必需在程序進(jìn)展捕獲和處置。異常處置機(jī)制主要處置檢查進(jìn)展捕獲和處置。異常處置機(jī)制主要處置檢查性異常。性異常。Java Exception Type Hierarchy(層次層次) virtual machine er
9、rors系統(tǒng)異常類的層次構(gòu)造:系統(tǒng)異常類的層次構(gòu)造:Exception的分類的分類nSystem-Defined Exception(系統(tǒng)定義的異常系統(tǒng)定義的異常)nProgrammer-Defined Exception(程序員自定程序員自定義異常義異常)System-Defined Exception(系統(tǒng)定義的異常系統(tǒng)定義的異常)nRaised implicitly by system because of illegal execution of program; nCreated by Java System automatically; nException extended fr
10、om Error class and RuntimeException class. System-Defined ExceptionlIndexOutOfBoundsException: lWhen beyond the bound of index in the object which use index, such as array, string, and vector lArrayStoreException: lWhen assign object of incorrect type to element of array lNegativeArraySizeException:
11、 lWhen using a negative size of array lNullPointerException: lWhen refer to object as a null pointerlSecurityException: lWhen violate security. Caused by security managerlIllegalMonitorStateException: lWhen the thread which is not owner of monitor involves wait or notify method Programmer-Defined Ex
12、ception (程序員自定義異常程序員自定義異常)n Exceptions raised by programmer nSubclass of Exception class nCheck by compiler whether the exception handler for exception occurred exists or notnIf there is no handler, it is error. User-defined Exceptions(用戶自定義異常用戶自定義異常)class UserErr extends Exception Creating Exceptio
13、n Types:Example 1:public class InsufficientFundsException extends Exception private BankAccount excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; 程序運(yùn)轉(zhuǎn)時(shí)發(fā)生異常,系統(tǒng)會(huì)拋出異常,假設(shè)程序中未處置程序運(yùn)轉(zhuǎn)時(shí)發(fā)生異常,系統(tǒng)會(huì)拋出異常,假設(shè)程序中未處置和捕獲異常,異常拋出后程序運(yùn)轉(zhuǎn)中斷。和捕獲異常,異常
14、拋出后程序運(yùn)轉(zhuǎ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)給出的錯(cuò)誤信息:系統(tǒng)給出的錯(cuò)誤信息:Exception in thread main java.la
15、ng.ArrayIndexOutOfBoundsException: 2at exception.Test.bar(Test.java:7)at exception.Test.main(Test.java:25)Handling Exceptions(處置異常處置異常)nThrowing an exception(拋出異常拋出異常)nWhen an error occurs within a method. nAn exception object is created and handed off to the runtime system(運(yùn)轉(zhuǎn)時(shí)系統(tǒng)運(yùn)轉(zhuǎn)時(shí)系統(tǒng)). The runtime
16、system must find the code to handle the error. nCatching an exception(捕獲異常捕獲異常)nThe runtime system(運(yùn)轉(zhuǎn)時(shí)系統(tǒng)運(yùn)轉(zhuǎ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)用調(diào)用) stack(堆棧堆棧).Keywords for Java ExceptionsltryMarks the start of a block ass
17、ociated 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 catch handler is complete.lthrowsDescribes the excep
18、tions 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.拋出異常拋出異常 throw, throwsl在一個(gè)方法的運(yùn)轉(zhuǎn)過程中,假設(shè)一個(gè)語句引起了錯(cuò)誤時(shí),含有這個(gè)語句的方法就會(huì)創(chuàng)建一個(gè)包含有關(guān)異常信息的異常對(duì)象,并將它傳送給Java運(yùn)轉(zhuǎn)時(shí)系統(tǒng)。l我們把生成異常對(duì)象并把它提交給運(yùn)轉(zhuǎn)時(shí)系統(tǒng)的過程稱為拋出(throw)異常。lthrow 在方法體中用throw手工拋
19、出異常;lthrows 在方法頭部間接拋出異常,即:聲明方法中能夠拋出的異常。1. 在方法體中用在方法體中用throw手工拋出異常手工拋出異常throw拋出異常拋出異常,可以是系統(tǒng)定義的異常,也可以是用戶自可以是系統(tǒng)定義的異常,也可以是用戶自定義的異常。定義的異常。語法格式:語法格式:或或例如例如:下面語句就拋出了一個(gè)下面語句就拋出了一個(gè)IOException異常:異常:throw new IOException();異常類名異常類名 對(duì)象名對(duì)象名 new 異常類構(gòu)造函數(shù);異常類構(gòu)造函數(shù);throw 對(duì)象名;對(duì)象名;throw new 異常類構(gòu)造函數(shù);異常類構(gòu)造函數(shù);throw Example
20、class 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.exp(i); 2. throws間接拋出異常間接拋出異常(聲明異常聲明異常)l一個(gè)方法不處置它產(chǎn)生的異常一個(gè)方法不處置它產(chǎn)生的異常,而是沿著調(diào)用層次向上傳送而是沿著調(diào)用層
21、次向上傳送,由由調(diào)用它的方法來處置這些異常調(diào)用它的方法來處置這些異常,叫聲明異常。叫聲明異常。l在定義方法時(shí)用在定義方法時(shí)用throws關(guān)鍵字將方法中能夠產(chǎn)生的異常間接拋關(guān)鍵字將方法中能夠產(chǎn)生的異常間接拋出。出。l假設(shè)一個(gè)方法能夠引發(fā)一個(gè)異常,但它本人卻沒有處置,那么假設(shè)一個(gè)方法能夠引發(fā)一個(gè)異常,但它本人卻沒有處置,那么應(yīng)該聲明異常,并讓其調(diào)用者來處置這個(gè)異常,這時(shí)就需求用應(yīng)該聲明異常,并讓其調(diào)用者來處置這個(gè)異常,這時(shí)就需求用throws關(guān)鍵字來指明方法中能夠引發(fā)的一切異常。關(guān)鍵字來指明方法中能夠引發(fā)的一切異常。類型類型 方法名方法名(參數(shù)列表參數(shù)列表) throws 異常列表異常列表 /代碼
22、代碼 Example 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; /拋出異常拋出異常 異常向上傳送Exampleclass ThrowStatement extends Exception public static void exp(int ptr) throws NullPointerExcep
23、tion if (ptr = 0) throw new NullPointerException(); public static void main(String args) int i = 0; ThrowStatement.exp(i); 運(yùn)轉(zhuǎn)結(jié)果: java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8)Exceptions - throwing multiple(多個(gè)多個(gè)) exceptionsA M
24、ethod can throw multiple exceptions. Multiple exceptions are separated by commas after the throws keyword:public class MyClass public int computeFileSize() throws IOException, ArithmeticException. Handling Exceptionsl在一個(gè)方法中,對(duì)于能夠拋出的異常,處置方式在一個(gè)方法中,對(duì)于能夠拋出的異常,處置方式有兩種:有兩種:l一個(gè)方法不處置它產(chǎn)生的異常一個(gè)方法不處置它產(chǎn)生的異常,只在方法頭
25、部聲明只在方法頭部聲明運(yùn)用運(yùn)用throws拋出異常,使異常沿著調(diào)用層次向上拋出異常,使異常沿著調(diào)用層次向上傳送傳送,由調(diào)用它的方法來處置這些異常。由調(diào)用它的方法來處置這些異常。l用用try-catch-finally語句對(duì)異常及時(shí)處置;語句對(duì)異常及時(shí)處置;Handling Exceptionspublic void replaceValue(String name, Object value) throws NoSuchAttributeException Attr attr=find(name); if(attr=null) throw new NoSuchAttributeExceptio
26、n(name); attr.setValue(value);try replaceValue(“att1, “newValue); catch(NoSuchAttributeException e) e.printStackTrace();當(dāng)replaceValue()方法被調(diào)用時(shí),調(diào)用者需處置異常。處置異常語句處置異常語句try-catch-finally的根本格式為:的根本格式為:try /能夠產(chǎn)生異常的代碼;能夠產(chǎn)生異常的代碼; /不能有其它語句分隔不能有其它語句分隔catch(異常類名異常類名 異常對(duì)象名異常對(duì)象名) / 異常處置代碼;異常處置代碼; /要處置的第一種異常要處置的第一種
27、異常catch(異常類名異常類名 異常對(duì)象名異常對(duì)象名) /異常處置代碼;異常處置代碼; /要處置的第二種異常要處置的第二種異常finally /最終處置缺省處置最終處置缺省處置Exceptions Syntax(語法語法)例如例如try / Code which might throw an exception/ . catch(FileNotFoundException x) / code to handle a FileNotFound exception catch(IOException x) / code to handle any other I/O exceptions cat
28、ch(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. close/ any open files, etc.Handling Exceptions(處置異常)try-catch 或或 try-catch-finally .Three statements help define how exce
29、ptions are handled:tryidentifies a block of statements within which an exception might be thrown;A try statement can have multiple catch statements associated with it.catch must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. Th
30、e statements are executed if an exception of a particular type occurs within the try block. Handling Exceptionsfinally (可選項(xiàng)可選項(xiàng))must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. Even if the
31、 try and catch block have a return statement in them, finally will still run.用用try-catch-finally語句對(duì)異常及時(shí)處置語句對(duì)異常及時(shí)處置Exampleclass ThrowStatement extends Exception public static void exp(int ptr) try if (ptr = 0) throw new NullPointerException();catch(NullPointerException e) public static void main(Stri
32、ng args) int i = 0; ThrowStatement.exp(i); 系統(tǒng)拋出異常后,捕獲異常,運(yùn)轉(zhuǎn)系統(tǒng)拋出異常后,捕獲異常,運(yùn)轉(zhuǎn)finally塊,程序運(yùn)轉(zhuǎn)繼續(xù)。塊,程序運(yùn)轉(zhuǎn)繼續(xù)。public class Test public void foo() try int a = new int2; a4 = 1; /* causes a runtime exception due to the index */ System.out.println(“Method: foo);/假設(shè)異常發(fā)生,不執(zhí)行假設(shè)異常發(fā)生,不執(zhí)行 catch (ArrayIndexOutOfBoundsExc
33、eption e) System.out.println(exception: + e.getMessage(); e.printStackTrace(); finally System.out.println(Finally block always execute!); public static void main(String args) Test t = new Test(); t.foo(); System.out.println(“Excecution after Exception!); /繼續(xù)執(zhí)行繼續(xù)執(zhí)行 運(yùn)轉(zhuǎn)結(jié)果:exception: 4java.lang.ArrayInd
34、exOutOfBoundsException: 4at exception.Test.foo(Test.java:8)at exception.Test.main(Test.java:20)Finally block always execute!Excecution after Exception!Exceptions -throwing multiple exceptionspublic void method1() MyClass anObject = new MyClass();try int theSize = anObjectputeFileSize(); catch(Arithm
35、eticException x) / . catch(IOException x) / . Exceptions -catching multiple exceptionsEach try block can catch multiple exceptions.Start with the most specific exceptionsFileNotFoundException is a subclass of IO ExceptionIt MUST appear before IOException in the catch listpublic void method1() FileIn
36、putStream aFile; try aFile = new FileInputStream(.);int aChar = aFile.read();/. catch(FileNotFoundException x) / . catch(IOException x) / . Exception -The catch-all HandlerSince all Exception classes are a subclass of the Exception class, a catch handler which catches Exception will catch all except
37、ions.It must be the last in the catch List.public void method1()FileInputStream aFile;try aFile = new FileInputStream(.);int aChar = aFile.read();/.catch(IOException x)/ .catch(Exception x)/ Catch All Exceptions User-defined Exceptions(用戶自定義異常用戶自定義異常)的處置的處置class UserErr extends Exception 用戶自定義異常是檢查性
38、異常用戶自定義異常是檢查性異常(checked exception),必需用必需用throw手工拋出并處置。手工拋出并處置。class UserClass UserErr x = new UserErr(); . if (val 1) throw x;/ThrowExample.javaclass IllegalValueException 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)轉(zhuǎn) System.out.println(Value2 =+val2); class ThrowExample public static void main(String args ) UserTrial values=
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 中級(jí)財(cái)務(wù)會(huì)計(jì)學(xué)知到課后答案智慧樹章節(jié)測(cè)試答案2025年春湖南工學(xué)院
- 四川工業(yè)科技學(xué)院《景觀設(shè)計(jì)(1)》2023-2024學(xué)年第一學(xué)期期末試卷
- 西南民族大學(xué)《化工機(jī)械強(qiáng)度與振動(dòng)》2023-2024學(xué)年第二學(xué)期期末試卷
- 洛陽理工學(xué)院《組織學(xué)與胚胎學(xué)(B)》2023-2024學(xué)年第二學(xué)期期末試卷
- 四川省資陽市2025屆五年級(jí)數(shù)學(xué)第二學(xué)期期末調(diào)研試題含答案
- 海南健康管理職業(yè)技術(shù)學(xué)院《中國(guó)古代文學(xué)A(V)》2023-2024學(xué)年第二學(xué)期期末試卷
- 大同煤炭職業(yè)技術(shù)學(xué)院《個(gè)案工作實(shí)務(wù)》2023-2024學(xué)年第二學(xué)期期末試卷
- 廣州華商學(xué)院《藥理學(xué)實(shí)驗(yàn)A》2023-2024學(xué)年第二學(xué)期期末試卷
- 古詩詞中煉字的好處
- 工程質(zhì)量控制中的常見問題與解決方案
- 2025廣東深圳證券交易所及其下屬單位信息技術(shù)專業(yè)人員招聘筆試參考題庫附帶答案詳解
- 汽車租賃項(xiàng)目投標(biāo)書
- 2024《整治形式主義為基層減負(fù)若干規(guī)定》全文課件
- 20以內(nèi)加減法口算題(10000道)(A4直接打印-每頁100題)
- GB/T 20416-2006自然保護(hù)區(qū)生態(tài)旅游規(guī)劃技術(shù)規(guī)程
- GB/T 12669-1990半導(dǎo)體變流串級(jí)調(diào)速裝置總技術(shù)條件
- 中醫(yī)護(hù)理技術(shù)操作并發(fā)癥的預(yù)防及處理教案資料
- 《中華人民共和國(guó)殘疾人證申請(qǐng)表》
- 《企業(yè)員工培訓(xùn)國(guó)內(nèi)外文獻(xiàn)綜述》4800字
- 《游擊隊(duì)歌》-完整版PPT
- DB11-T 1832.8-2022建筑工程施工工藝規(guī)程 第8部分:門窗工程
評(píng)論
0/150
提交評(píng)論