版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、Java程序設計,Java Programming Spring, 2009,chapter 8 Exceptions,2/25,Contents,Why Exceptions? What are Exceptions? Handling Exceptions Creating Exception Types,chapter 8 Exceptions,3/25,Why Exceptions?,During execution, programs can run into many kinds of errors; What do we do when an error occurs? Java
2、 uses exceptions to provide the error-handling capabilities for its programs.,chapter 8 Exceptions,4/25,Exceptions,Error Class Critical error which is not acceptable in normal application program. Exception Class Possible exception in normal application program execution; Possible to handle by progr
3、ammer.,chapter 8 Exceptions,5/25,Exceptions,An exception is an event that occurs during the execution of a program that disrupts(使中斷) the normal flow of instructions. Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a prog
4、rammer makes new exception class to extend the Exception class which is a subclass of Throwable class.,6,7,異常類的層次結構:,8,Classifying Java Exceptions,Unchecked ExceptionsIt is not required that these types of exceptions be caught or declared on a method. Runtime exceptions can be generated by methods o
5、r by the JVM itself. Errors are generated from deep within the JVM, and often indicate a truly fatal state.,Checked ExceptionsMust either be caught by a method or declared in its signature by placing exceptions in the method signature.,chapter 8 Exceptions,9/25,Exception的分類,檢查性異常(checked exception):
6、 一般程序中可預知的問題,其產(chǎn)生的例外可能會帶來意想不到的結果,因此Java編譯器要求Java程序必須捕獲或聲明所有的非運行時異常。以IOException為代表的一些類。如果代碼中存在檢查性異常,必須進行異常處理,否則編譯不能通過。如:用戶連接數(shù)據(jù)庫SQLException、FileNotFoundException。 非檢查性異常(unchecked exception): 以RuntimeException為代表的一些類,編譯時發(fā)現(xiàn)不了,只在能運行時才能發(fā)現(xiàn)。,chapter 8 Exceptions,10/25,Exception的分類,Runtime Exception: Java虛
7、擬機在運行時生成的例外,如被0除等系統(tǒng)錯誤、數(shù)組下標超范圍等,其產(chǎn)生比較頻繁,處理麻煩,對程序可讀性和運行效率影響太大。因此由系統(tǒng)檢測, 用戶可不做處理,系統(tǒng)將它們交給缺省的異常處理程序(當然,必要時,用戶可對其處理)。 Java程序異常處理的原則是: 對于Error和RuntimeException,可以在程序中進行捕獲和處理,但不是必須的。 對于IOException及其他異常,必須在程序進行捕獲和處理。異常處理機制主要處理檢查性異常。,chapter 8 Exceptions,11/25,異常類的層次結構:,chapter 8 Exceptions,12/25,System-Define
8、d Exception(系統(tǒng)定義的異常),Raised implicitly by system because of illegal execution of program; When cannot continue program execution any more; Created by Java System automatically; Exception extended from Error class and RuntimeException class.,13/25,System-Defined Exception,IndexOutOfBoundsException :
9、When beyond the bound of index in the object which use index, such as array, string, and vector ArrayStoreException : When assign object of incorrect type to element of array NegativeArraySizeException : When using a negative size of array NullPointerException : When refer to object as a null pointe
10、r SecurityException : When violate security. Caused by security manager IllegalMonitorStateException : When the thread which is not owner of monitor involves wait or notify method,14,Programmer-Defined Exception,Exceptions raised by programmer Check by compiler whether the exception handler for exce
11、ption occurred exists or not If there is no handler, it is error Sub class of Exception class,chapter 8 Exceptions,15/25,Handling Exceptions,Throwing an exception When an error occurs within a method. An exception object is created and handed off to the runtime system. The runtime system must find t
12、he code to handle the error. Catching an exception The system searches for code to handle the thrown exception. It can be in the same method or in some method in the call stack.,chapter 8 Exceptions,16/25,Keywords for Java Exceptions,throwsDescribes the exceptions which can be raised by a method. th
13、rowRaises an exception to the first available handler in the call stack, unwinding the stack along the way. tryMarks the start of a block associated with a set of exception handlers. catchIf the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit
14、 subsumption. finallyAlways called when the try block concludes, and after any necessary catch handler is complete.,17,Exception Occurrence,throws Statement When programmer-defined exception is raised, if there is no exception handler, need to describe it in the declaration part of method Exception1
15、.java,modifiers returntype methodName(params) throws e1, . ,ek ,18,Example,public class exception1 void Proc(int sel) throws ArithmeticException,ArrayIndexOutOfBoundsException System.out.println(“In Situation + sel ); if(sel=0) System.out.println(no Exception caught); return; if(sel=1) int iArray=ne
16、w int4; iArray10=3; ,19,Exception Occurrence,Raised implicitly by system Raised explicitly by programmer throw Statement ThrowStatement.java,throw ThrowableObject;,Throwable class or its sub class,20,Exception OccurrenceExample,class ThrowStatement extends Exception public static void exp(int ptr) i
17、f (ptr = 0) throw new NullPointerException(); public static void main(String args) int i = 0; ThrowStatement.exp(i); ,運行結果: java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8),21,Throwing Exceptions,You can throw exceptions from y
18、our own methods To throw an exception, create an instance of the exception class and throw it. If you throw checked exceptions, you must indicate which exceptions your method throws by using the throws keyword,public void withdraw(float anAmount) throws InsufficientFundsException if(anAmountbalance)
19、 throw new InsuffientFundsException(Not enough cash); balance = balance - anAmount; ,22,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 catch(Ex
20、ception 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. ,23,該語句的基本格式為:,try 可能產(chǎn)生異常的代碼; /不能有其它語句分隔 catch(異常類名 異常對象名) 異常處理代碼; /要處理的第一種異常 catch(異常類名 異常對象名)
21、異常處理代碼; /要處理的第二種異常 finally 最終處理(缺省處理) ,24/25,Handling Exceptions,try-catch 或 try-catch-finally . Three statements help define how exceptions are handled: try identifies a block of statements within which an exception might be thrown; catch must be associated with a try statement and identifies a blo
22、ck 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. A try statement can have multiple catch statements associated with it.,chapter 8 Exceptions,25/25,Handling Exceptions,finally must be associa
23、ted 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 try and catch block have a return statement in them, finally will still run.,26,Exceptions -Defining checked exceptions,Any code which throws
24、 a checked exception MUST be placed within a try block. Checked exceptions are defined using the throws keyword in the method definition:,public class PrintReader extends Reader public int read() throws IOException . ,public void method1() PrintReader aReader; . initialize reader . try int theCharac
25、ter = aReader.read(); catch(IOException x) . ,27,Handling Exceptions,public void replaceValue(String name, Object value) throws NoSuchAttributeException Attr attr=find(name); if(attr=null) throw new NoSuchAttributeException(name); attr.setValue(value); try replaceValue(“att1”, “newValue”); catch(NoS
26、uchAttributeException e) e.printStackTrace(); ,28,Exceptions -throwing multiple exceptions,A Method can throw multiple exceptions. Multiple exceptions are separated by commas after the throws keyword:,public class MyClass public int computeFileSize() throws IOException, ArithmeticException . ,29,Exc
27、eptions -throwing multiple exceptions,public void method1() MyClass anObject = new MyClass(); try int theSize = anOputeFileSize(); catch(ArithmeticException x) / . catch(IOException x) / .,30,Exceptions -catching multiple exceptions,Each try block can catch multiple exceptions. Start with the most s
28、pecific exceptions FileNotFoundException is a subclass of IO Exception It MUST appear before IOException in the catch list,public void method1() FileInputStream aFile; try aFile = new FileInputStream(.); int aChar = aFile.read(); /. catch(FileNotFoundException x) / . catch(IOException x) / . ,31,Exc
29、eption -The catch-all Handler,Since 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
30、.read(); /. catch(IOException x) / . catch(Exception x) / Catch All Exceptions ,32,Example with try-catch-finally,/* class example FileIn.java */ /* assumes each char is one byte - dangerous import java.io.*; public class FileIn public static void main(String args) try FileInputStream fin = new File
31、InputStream(“c:javatest.java”); int input; while (input = fin.read()!= -1) System.out.print(char)input); catch(IOException ie) System.out.println(e); finally fin.close(); ,chapter 8 Exceptions,33/25,User-defined Exceptions,class UserClass UserErr x = new UserErr(); / . if (val 1) throw x; ,class Use
32、rErr extends Exception ,Creating Exception Types:,chapter 8 Exceptions,34/25,Example 1,public class InsufficientFundsException extends Exception private Bank excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; ,35/25,class Ban
33、k double balance; Bank(double dAmount) balance= dAmount; public void deposite(double dAmount) if(dAmount0.0) balance+=dAmount; public void withdrawal(double dAmount) throws InsufficientFundsException if (balancedAmount) throw new InsufficientFundsException(this,dAmount); balance=balance-dAmount; pub
34、lic String show_balance() String str=The balance is +(int)balance; System.out.println(str); return str; ,36,Example 1,public class ExceptionDemo public static void main(String args) try Bank ba=new Bank(50); ba.withdrawal(100); System.out.println(“Withdrawal successful!”); catch(InsufficientFundsExc
35、eption e) System.out.println(e.toString(); System.out.println(e.excepMessage(); ,37,/Example 2*ThrowExample.java*,class 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
36、IllegalValueException(); System.out.println(Value1=+ val1); System.out.println(Value2 =+val2); ,class ThrowExample public static void main(String args) UserTrial values=new UserTrial(-1,1); try values.show(); catch (IllegalValueException e) System.out.println(Illegal Values: Caught in main); ,chapter 8
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2026年智能停車輔助系統(tǒng)項目公司成立分析報告
- 2025年中職水利水電工程施工(水工建筑物基礎)試題及答案
- 2026年家政服務教學(家政服務應用)試題及答案
- 2025年高職防災減災技術(災害預防措施)試題及答案
- 2025年高職物理學(相對論)試題及答案
- 2025年中職作曲與作曲技術理論(作曲理論)試題及答案
- 2025年中職(茶葉生產(chǎn)與加工)茶葉采摘標準試題及答案
- 2025年大學大四(印刷企業(yè)管理)企業(yè)運營專項測試題及答案
- 2025年大學生態(tài)環(huán)境保護(生態(tài)修復工程)試題及答案
- 2025年高職數(shù)字媒體藝術設計(數(shù)字插畫創(chuàng)作)試題及答案
- 手術室查對制度
- 支氣管哮喘患者的自我管理宣教
- 第三次全國國土調查工作分類與三大類對照表
- 質量效應2楷模路線文字版
- 消防設施檢查記錄表
- 酒店協(xié)議價合同
- 哈爾濱工業(yè)大學簡介宣傳介紹
- 青光眼的藥物治療演示
- 羅永浩海淀劇場演講
- 蘇州市公務員考核實施細則
- GB/T 2703-2017鞋類術語
評論
0/150
提交評論