【正文】
(package) package 。d:\src2。 determine its size。 } 潛在的問題 : ? What happens if the file can39。t be closed? readFile { try { open the file。 close the file。 } catch (readFailed) { doSomething。 } method3 { call readFile。 else proceed。 else proceed。 else proceed。 } method3 throws exception { call readFile。 read the file into memory。 allocate that much memory。 } catch (sizeDeterminationFailed) { doSomething。 } } 24 ? 對異常的定義 ? Java語言中定義的異常類 : IOException/NullPointerException ? 詳細定義見 Java文檔中各個包的 Exception Summary ? 用戶定義自已所需的異常類,描述程序中出現(xiàn)的異常結果 第 10講 異常 (Exception) class class (嚴重的問題,但不需程序捕捉的錯誤 ) class ... ... class class class ... ... class (程序應該捕捉的錯誤 ) class class (JVM正常運行時拋出的錯誤 ) class ... ... class class class ... ... 25 ? 何時會出現(xiàn)異常 ? ? 方法中已定義了異常的拋出 異常 (Exception) import 。 (Received char= + c)。 (i)。 } } import 。 } } } unreported exception 。 (c)。 } 30 ? 異常處理器 (exception handler) ? finally語句塊 ? There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block. ? finally語句塊在異常處理中是必須執(zhí)行的語句塊 ? 清理現(xiàn)場 ? 關閉打開的文件 ? 關閉網(wǎng)絡連接 異常 (Exception) try { // The guarded region: Dangerous activities // that might throw A, B, or C } catch(A a1) { // Handler for situation A } catch(B b1) { // Handler for situation B } catch(C c1) { // Handler for situation C } finally { // Activities that happen every time } 31 ? 異常的拋出 ? 在一個方法中,拋出異常,同時捕捉 ? 當有多個方法調用時,由特定 (適當 )的方法捕捉異常 ? 被調用的方法主動拋出異常 (throws) 異常 (Exception) import 。 (c)。 } 33 ? 自定義異常 ? 使用 JAVA已有的異常 ?異常的拋出 /捕捉 ? 定義自已特有的異常 ?異常的拋出 /捕捉 異常 (Exception) class SimpleException extends Exception {} public class SimpleExceptionDemo { public void f() throws SimpleException { (Throw SimpleException from f())。 } catch(SimpleException e) { (e)。 public MyException() {} public MyException(String msg) { super(msg)。 throw new MyException()。 throw new MyException(Originated in h(), 47)。 MyException f om g() MyException: Originated in g() om h()in h()h()。 therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not pile. 第八講 結束 !