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

下載本文檔

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

文檔簡介

1、Java程序設(shè)計Java ProgrammingSpring, 20131ContentsWhy Exceptions?What are Exceptions?Handling ExceptionsCreating Exception Types2Why Exceptions(異常)?During execution(執(zhí)行), programs can run into many kinds of errors;What do we do when an error occurs?Java uses exceptions to provide the error-handling capabi

2、lities for its programs.3Exceptions (異常)Error ClassCritical(嚴重的) error which is not acceptable in normal application program. Exception ClassPossible exception in normal application program execution; Possible to handle by programmer. 4Exceptions (異常)An exception is an event(事件) that occurs during t

3、he execution of a program that disrupts(使中斷) the normal flow(流程) of instructions(指令).5Exceptions (異常)Treat exception as an object .All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a programmer makes new exception class to extend the Exception class wh

4、ich is a subclass of Throwable class.6Exception Class 繼承關(guān)系ThrowableErrorExceptionRuntimeExceptionIOExceptionObject7異常類的層次結(jié)構(gòu):8Classifying(分類) Java ExceptionsUnchecked Exceptions(非檢查性異常)It is not required that these types of exceptions be caught or declared on a method.Runtime exceptions can be genera

5、ted 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.9Exception的分類非檢查性異常(unchecked exception):以Ru

6、ntimeException為代表的一些類,編譯時發(fā)現(xiàn)不了,只在能運行時才能發(fā)現(xiàn)。檢查性異常(checked exception):一般程序中可預知的問題,其產(chǎn)生的異??赡軙硪庀氩坏降慕Y(jié)果,因此Java編譯器要求Java程序必須捕獲或聲明所有的非運行時異常。以IOException為代表的一些類。如果代碼中存在檢查性異常,必須進行異常處理,否則編譯不能通過。如:用戶連接數(shù)據(jù)庫SQLException、。10Exception的分類什么是Runtime Exception:Java虛擬機在運行時生成的異常,如:被0除等系統(tǒng)錯誤、數(shù)組下標超范圍等,其產(chǎn)生比較頻繁,處理麻煩,對程序可讀性和運行效

7、率影響太大。因此由系統(tǒng)檢測, 用戶可不做處理,系統(tǒng)將它們交給默認的異常處理程序(當然,必要時,用戶可對其處理)。Java程序異常處理的原則是:對于Error和RuntimeException,可以在程序中進行捕獲和處理,但不是必須的。對于IOException及其他異常,必須在程序進行捕獲和處理。異常處理機制主要處理檢查性異常。11Java Exception Type Hierarchy(層次) virtual machine errors12系統(tǒng)異常類的層次結(jié)構(gòu):13Exception的分類System-Defined Exception(系統(tǒng)定義的異常)Programmer-Define

8、d Exception(程序員自定義異常)14System-Defined Exception(系統(tǒng)定義的異常)Raised implicitly by system because of illegal execution of program; Created by Java System automatically; Exception extended from Error class and RuntimeException class. 15System-Defined ExceptionIndexOutOfBoundsException: When beyond the boun

9、d 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 pointerSecurityException: Whe

10、n violate security. Caused by security managerIllegalMonitorStateException: When the thread which is not owner of monitor involves wait or notify method 16Programmer-Defined Exception (程序員自定義異常) Exceptions raised by programmer Subclass of Exception class Check by compiler whether the exception handl

11、er for exception occurred exists or notIf there is no handler, it is error. 17User-defined Exceptions(用戶自定義異常)class UserErr extends Exception Creating Exception Types:18Example 1:public class InsufficientFundsException extends Exception private BankAccount excepbank; private double excepAmount; Insu

12、fficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; 19程序運行時發(fā)生異常,系統(tǒng)會拋出異常,如果程序中未處理和捕獲異常,異常拋出后程序運行中斷。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.ba

13、r();/程序中斷 System.out.println(“Method: foo”); /不被執(zhí)行 系統(tǒng)給出的錯誤信息:Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 2at exception.Test.bar(Test.java:7)at exception.Test.main(Test.java:25)20Handling Exceptions(處理異常)Throwing an exception(拋出異常)When an error occurs within a method. An except

14、ion object is created and handed off to the runtime system(運行時系統(tǒng)). The runtime system must find the code to handle the error. Catching an exception(捕獲異常)The runtime system(運行時系統(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(堆棧

15、).21Keywords for Java ExceptionstryMarks 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 subsumption.finallyAlways called when the try block concludes, and after any

16、 necessary catch handler is complete.throwsDescribes the exceptions which can be raised by a method.throwRaises an exception to the first available handler in the call stack, unwinding the stack along the way.22拋出異常 throw, throws在一個方法的運行過程中,如果一個語句引起了錯誤時,含有這個語句的方法就會創(chuàng)建一個包含有關(guān)異常信息的異常對象,并將它傳遞給Java運行時系統(tǒng)。我

17、們把生成異常對象并把它提交給運行時系統(tǒng)的過程稱為拋出(throw)異常。throw 在方法體中用throw手工拋出異常;throws 在方法頭部間接拋出異常,即:申明方法中可能拋出的異常。231. 在方法體中用throw手工拋出異常throw拋出異常,可以是系統(tǒng)定義的異常,也可以是用戶自定義的異常。語法格式:或例如:下面語句就拋出了一個IOException異常:throw new IOException();異常類名 對象名 new 異常類構(gòu)造函數(shù);throw 對象名;throw new 異常類構(gòu)造函數(shù);24throw Exampleclass ThrowStatement extends

18、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); 252. throws間接拋出異常(申明異常)一個方法不處理它產(chǎn)生的異常,而是沿著調(diào)用層次向上傳遞,由調(diào)用它的方法來處理這些異常,叫聲明異常。在定義方法時用throws關(guān)鍵字將方法中可能產(chǎn)生的異常間接拋出。若一個方

19、法可能引發(fā)一個異常,但它自己卻沒有處理,則應(yīng)該聲明異常,并讓其調(diào)用者來處理這個異常,這時就需要用throws關(guān)鍵字來指明方法中可能引發(fā)的所有異常。類型 方法名(參數(shù)列表) throws 異常列表 /代碼 26Example 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; /拋出異常 27異常向上傳遞Ex

20、ampleclass ThrowStatement 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); 運行結(jié)果: java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java

21、:4) at ThrowStatement.main(ThrowStatement.java:8)28Exceptions - throwing multiple(多個) exceptionsA Method can throw multiple exceptions. Multiple exceptions are separated by commas after the throws keyword:public class MyClass public int compute() throws IOException, ArithmeticException. 29Handling E

22、xceptions在一個方法中,對于可能拋出的異常,處理方式有兩種:一個方法不處理它產(chǎn)生的異常,只在方法頭部聲明使用throws拋出異常,使異常沿著調(diào)用層次向上傳遞,由調(diào)用它的方法來處理這些異常。用try-catch-finally語句對異常及時處理;30Handling Exceptionspublic void replaceValue(String name, Object value) throws NoSuchAttributeException Attr attr=find(name); if(attr=null) throw new NoSuchAttributeExceptio

23、n(name); attr.setValue(value);try replaceValue(“att1”, “newValue”); catch(NoSuchAttributeException e) e.printStackTrace();當replaceValue()方法被調(diào)用時,調(diào)用者需處理異常。31處理異常語句try-catch-finally的基本格式為:try /可能產(chǎn)生異常的代碼; /不能有其它語句分隔catch(異常類名 異常對象名) / 異常處理代碼; /要處理的第一種異常catch(異常類名 異常對象名) /異常處理代碼; /要處理的第二種異常finally /最終處理(

24、缺省處理)32Exceptions Syntax(語法)示例try / Code which might throw an exception/ . catch( x) / code to handle a 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

25、was thrown/ or not. A good place to put clean-up code. ie. close/ any open files, etc.33Handling Exceptions(處理異常)try-catch 或 try-catch-finally .Three statements help define how exceptions are handled:tryidentifies a block of statements within which an exception might be thrown;A try statement can ha

26、ve 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. The statements are executed if an exception of a particular type occurs within the try block. 34Handling Exceptionsfinall

27、y (可選項)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 try and catch block have a return statement in them, finally will still run.35用try-catch-finally語句對異常及時處理Exampleclass T

28、hrowStatement 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); 36系統(tǒng)拋出異常后,捕獲異常,運行finally塊,程序運行繼續(xù)。public class Test public void foo() try int a = new

29、int2; a4 = 1; /* causes a runtime exception due to the index */ System.out.println(“Method: foo”);/若異常發(fā)生,不執(zhí)行 catch (ArrayIndexOutOfBoundsException e) System.out.println(exception: + e.getMessage(); e.printStackTrace(); finally System.out.println(Finally block always execute!); public static void mai

30、n(String args) Test t = new Test(); t.foo(); System.out.println(“Excecution after Exception!”); /繼續(xù)執(zhí)行 37運行結(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!38Exceptio

31、ns -throwing multiple exceptionspublic void method1() MyClass anObject = new MyClass();try int theSize = anOpute(); catch(ArithmeticException x) / . catch(IOException x) / . 39Exceptions -catching multiple exceptionsEach try block can catch multiple exceptions.Start with the most specific exceptions

32、 is a subclass of IO ExceptionIt MUST appear before IOException in the catch listpublic void method1() aFile; try aFile = new (.);int aChar = a();/. catch( x) / . catch(IOException x) / . 40Exception -The catch-all HandlerSince all Exception classes are a subclass of the Exception class, a catch han

33、dler which catches Exception will catch all exceptions.It must be the last in the catch List.public void method1() aFile;try aFile = new (.);int aChar = a();/.catch(IOException x)/ .catch(Exception x)/ Catch All Exceptions 41User-defined Exceptions(用戶自定義異常)的處理class UserErr extends Exception 用戶自定義異常是

34、檢查性異常(checked exception),必須用throw手工拋出并處理。class UserClass UserErr x = new UserErr(); . if (val 1) throw x;42/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)

35、throw new 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

溫馨提示

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

評論

0/150

提交評論