Microsoft PowerPoint - ch15.ppt

Similar documents
chp6.ppt

1: public class MyOutputStream implements AutoCloseable { 3: public void close() throws IOException { 4: throw new IOException(); 5: } 6:

3.1 num = 3 ch = 'C' 2

Microsoft PowerPoint - 13_Exception.ppt

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

2/80 2

EJB-Programming-4-cn.doc

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Microsoft Word - 投影片ch13

Chapter 9: Objects and Classes

Microsoft Word - JAVA Programming Language Homework I ans

投影片 1

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

Chapter 9: Objects and Classes

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

《大话设计模式》第一章

Microsoft Word - ch04三校.doc

untitled

untitled

Chapter 9: Objects and Classes

EJB-Programming-3.PDF

Microsoft Word - 01.DOC

基于CDIO一体化理念的课程教学大纲设计

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

JBuilder Weblogic

Java 1 Java String Date

Microsoft PowerPoint - Lecture7II.ppt

Microsoft Word - Learn Objective-C.doc

Microsoft Word - 11.doc

任務二 : 產生 20 個有炸彈的磚塊, 放在隨機的位置編輯 Block 類別的程式碼 import greenfoot.; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) Write a description of class

Microsoft PowerPoint - L17_Inheritance_v4.pptx

untitled

Learning Java

Java

C++ 程式設計

Microsoft Word - JAVA Programming Language Homework VI_ans.doc

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

epub83-1

Microsoft Word - 物件導向編程精要.doc

使 用 Java 语 言 模 拟 保 险 箱 容 量 门 板 厚 度 箱 体 厚 度 属 性 锁 具 类 型 开 保 险 箱 关 保 险 箱 动 作 存 取 款

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO

Python a p p l e b e a r c Fruit Animal a p p l e b e a r c 2-2

untitled

mvc

untitled

OOP with Java 通知 Project 4: 4 月 18 日晚 9 点 关于抄袭 没有分数

CC213

A Preliminary Implementation of Linux Kernel Virus and Process Hiding

概述

9, : Java 19., [4 ]. 3 Apla2Java Apla PAR,Apla2Java Apla Java.,Apla,,, 1. 1 Apla Apla A[J ] Get elem (set A) A J A B Intersection(set A,set B) A B A B

Microsoft PowerPoint - SE7ch10.ppt

Microsoft Word - (web)_F.1_Notes_&_Application_Form(Chi)(non-SPCCPS)_16-17.doc

2009年3月全国计算机等级考试二级Java语言程序设计笔试试题

untitled

Microsoft Word - CX VMCO 3 easy step v1.doc

JavaIO.PDF

AN INTRODUCTION TO PHYSICAL COMPUTING USING ARDUINO, GRASSHOPPER, AND FIREFLY (CHINESE EDITION ) INTERACTIVE PROTOTYPING

内 容 简 介 本 书 是 一 本 关 于 语 言 程 序 设 计 的 教 材, 涵 盖 了 语 言 的 基 本 语 法 和 编 程 技 术, 其 中 包 含 了 作 者 对 语 言 多 年 开 发 经 验 的 总 结, 目 的 是 让 初 学 的 读 者 感 受 到 语 言 的 魅 力, 并 掌

Microsoft Word doc

D C 93 2

Microsoft Word - 苹果脚本跟我学.doc

K301Q-D VRT中英文说明书141009

Microsoft Word - template.doc

untitled

C/C++ 语言 - 循环

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F


2015年4月11日雅思阅读预测机经(新东方版)

Microsoft PowerPoint - EmbSys101_Java Basics.ppt [相容模式]

DbC vs. Exception

中国人民大学商学院本科学年论文

尽 管 Java 语 言 是 在 C++ 语 言 基 础 上 发 展 起 来 的, 但 是 有 别 于 C++,Java 是 一 种 纯 粹 的 面 向 对 象 语 言 (Object-oriented language) 在 像 Java 这 样 纯 粹 的 面 向 对 象 语 言 中, 所 有

Windows XP

運算子多載 Operator Overloading

INTRODUCTION TO COM.DOC

第7章-并行计算.ppt

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

OOP with Java 通知 Project 4: 5 月 2 日晚 9 点

软件测试(TA07)第一学期考试

高中英文科教師甄試心得

1 C++ 2 Bjarne Stroustrup C++ (system programming) 6 (infrastructure) C++ 7 Herb Sutter 8 C++ (efficiency) (flexibility) 9 (abstraction) (productivity

untitled

穨control.PDF

Microsoft PowerPoint - plan08.ppt

入學考試網上報名指南

附录J:Eclipse教程

<4D F736F F F696E74202D20C8EDBCFEBCDCB9B9CAA6D1D0D0DEBDB2D7F92E707074>

Collection of 2012 Examination Certificates

中 文 摘 要 智 慧 型 手 機 由 於 有 強 大 的 功 能, 以 及 優 渥 的 便 利 性, 還 能 與 網 路 保 持 隨 時 的 鏈 結 與 同 步 更 新, 因 此 深 受 廣 大 消 費 者 喜 愛, 當 然, 手 機 遊 戲 也 成 為 現 代 人 不 可 或 缺 的 娛 樂 之

Swing-02.pdf

Android Service

OOP with Java 通知 Project 4: 4 月 19 日晚 9 点

FY.DOC

RunPC2_.doc

Strings

目次 

Microsoft PowerPoint - course2.ppt

VHDL(Statements) (Sequential Statement) (Concurrent Statement) VHDL (Architecture)VHDL (PROCESS)(Sub-program) 2

基于ECO的UML模型驱动的数据库应用开发1.doc

Transcription:

Exception Handling Exception handling Exception Indication of problem during execution E.g., divide by zero Chained exceptions 1 Exception-Handling Overview Uses of exception handling Process exceptions from program components Handle exceptions in a uniform manner in large projects Remove error-handling code from main line of execution A method detects an error and throws an exception Exception handler processes the error Uncaught exceptions yield adverse effects Might terminate program execution 2 1

Exception-Handling Overview Code that could generate errors put in try blocks Code for error handling enclosed in a catch clause The finally clause always executes Termination model of exception handling The block in which the exception occurs expires throws clause specifies exceptions method throws Divide by Zero Common programming mistake Throws ArithmeticException 3 程式錯誤的分類 程式的錯誤可以依照性質分成三種 : 編譯期錯誤 : 編譯時所發生的錯誤, 經常是語法錯 執行期錯誤 : 在編譯程式的過程中不容易發現, 常在程式執行的過程中發生的錯誤 邏輯錯誤 : 程式設計者在設計程式時, 所發生的邏輯上的問題 4 2

Java 例外的繼承關係 錯誤或例外都是 java.lang.throwable 的延伸類別 Error 及其延伸類別 : 其為嚴重的錯誤, 通常捕捉到也無法處理, 因此也很少去捕捉 Exception 及其延伸類別 ( 不包含 RuntimeException 及其延伸類別 ): 這類例外在一般情況很可能發生, 大多屬於環境問題 RuntimeException 及其延伸類別 : 此類例外為程式的執行期錯誤, 例如, 某數除以 0 陣列索引值超出範圍等 5 java.lang.object java.lang.throwable java.lang.error java.lang.virtualmachineerror java.lang.exception java.io.ioexception java.lang.classnotfoundexception java.lang.runtimeexception java.lang.arithmeticexception java.lang.arraystoreexception java.lang.illegalargumentexception java.lang.numberformatexception java.lang.illegalstateexception java.lang.indexoutofboundsexception java.lang.arrayindexoutofboundsexception java.lang.stringindexoutofboundsexception java.lang.nullpointerexception 6 3

RuntimeException 常見的 RuntimeException(Unchecked Exception) 執行期例外 ArithmeticException ArrayIndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException 說明 數學運算時的例外 例如 : 某數除以 0 陣列索引值超出範圍 陣列的大小為負數 物件參照為 null, 並使用物件成員時所產生的例外 數值格式不符所產生的例外 7 27 28 // set up label and inputfield2; register listener 29 container.add( new JLabel( "Enter denominator and press Enter ", 30 SwingConstants.RIGHT ) ); 31 inputfield2 = new JTextField(); 32 container.add( inputfield2 ); 33 inputfield2.addactionlistener( this ); 34 35 // set up label and outputfield 36 container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) ); 37 outputfield = new JTextField(); 38 container.add( outputfield ); 39 40 setsize( 425, 100 ); 41 setvisible( true ); 42 43 } // end DivideByZeroTest constructor 44 45 // process GUI events 46 public void actionperformed( ActionEvent event ) 47 { 48 outputfield.settext( "" ); // clear outputfield 49 50 // read two numbers and calculate quotient 51 try { 52 number1 = Integer.parseInt( inputfield1.gettext() ); 53 number2 = Integer.parseInt( inputfield2.gettext() ); DivideByZeroTest.j ava Line 51 Lines 52-53 4

54 55 result = quotient( number1, number2 ); 56 outputfield.settext( String.valueOf( result ) ); 57 } 58 59 // process improperly formatted input 60 catch ( NumberFormatException numberformatexception ) { 61 JOptionPane.showMessageDialog( this, 62 "You must enter two integers", "Invalid Number Format", 63 JOptionPane.ERROR_MESSAGE ); 64 } 65 66 // process attempts to divide by zero 67 catch ( ArithmeticException arithmeticexception ) { 68 JOptionPane.showMessageDialog( this, 69 arithmeticexception.tostring(), "Arithmetic Exception", 70 JOptionPane.ERROR_MESSAGE ); 71 } 72 73 } // end method actionperformed 74 75 // demonstrates throwing an exception when a divide-by-zero occurs 76 public int quotient( int numerator, int denominator ) 77 throws ArithmeticException 78 { 79 return numerator / denominator; 80 } DivideByZeroTest.j ava Line 55 Line 60 Line 67 Line 77 81 82 public static void main( String args[] ) 83 { 84 DivideByZeroTest application = new DivideByZeroTest(); 85 application.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 86 } 87 88 } // end class DivideByZeroTest DivideByZeroTest.j ava 5

Superclass Throwable Java Exception Hierarchy Subclass Exception Exceptional situations Should be caught by program Subclass Error Typically not caught by program Checked exceptions Catch or declare Unchecked exceptions 11 Inheritance hierarchy for class Throwable Throwable Exception Error RuntimeException IOException AWTError ThreadDeath OutOfMemoryError 12 6

Rethrowing an Exception Rethrow exception if catch cannot handle it 13 finally Clause Resource leak Caused when resources are not released by a program The finally block Appears after catch blocks Always executes Use to release resources 14 7

1 // Fig. 15.3: UsingExceptions.java 2 // Demonstration of the try-catch-finally exception handling mechanism. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 throwexception(); // call method throwexception 9 } 10 11 // catch Exceptions thrown by method throwexception 12 catch ( Exception exception ) { 13 System.err.println( "Exception handled in main" ); 14 } 15 16 doesnotthrowexception(); 17 } 18 19 // demonstrate try/catch/finally 20 public static void throwexception() throws Exception 21 { 22 // throw an exception and immediately catch it 23 try { 24 System.out.println( "Method throwexception" ); 25 throw new Exception(); // generate exception 26 } UsingExceptions.ja va 27 28 // catch exception thrown in try block 29 catch ( Exception exception ) { 30 System.err.println( 31 "Exception handled in method throwexception" ); 32 throw exception; // rethrow for further processing 33 34 // any code here would not be reached 35 } 36 37 // this block executes regardless of what occurs in try/catch 38 finally { 39 System.err.println( "Finally executed in throwexception" ); 40 } 41 42 // any code here would not be reached 43 44 } // end method throwexception 45 46 // demonstrate finally when no exception occurs 47 public static void doesnotthrowexception() 48 { 49 // try block does not throw an exception 50 try { 51 System.out.println( "Method doesnotthrowexception" ); 52 } UsingExceptions.ja va Line 32 Lines 38-40 8

53 54 // catch does not execute, because no exception thrown 55 catch ( Exception exception ) { 56 System.err.println( exception ); 57 } 58 59 // this clause executes regardless of what occurs in try/catch 60 finally { 61 System.err.println( 62 "Finally executed in doesnotthrowexception" ); 63 } 64 65 System.out.println( "End of method doesnotthrowexception" ); 66 67 } // end method doesnotthrowexception 68 69 } // end class UsingExceptions UsingExceptions.ja va Lines 60-63 Method throwexception Exception handled in method throwexception Finally executed in throwexception Exception handled in main Method doesnotthrowexception Finally executed in doesnotthrowexception End of method doesnotthrowexception try{ // 例外測試區 } catch( 例外型別例外名 ){ // 例外處理區 } try-catch 敘述 try-catch 敘述用以捕捉並處理例外 只要是 Throwable 或其延伸類別之物件, 都可以使用 try-catch 敘述捕捉 18 9

多個 catch 區塊 try-catch 敘述可以使用多個 catch 區塊 try { // 例外測試區 } catch( 例外型別 1 例外名 1){ // 例外處理區 1 } catch( 例外型別 2 例外名 2){ // 例外處理區 2 }... catch( 例外型別 N 例外名 N){ // 例外處理區 N } 19 多個 catch 區塊 頂多只會有一個 catch 區塊內的敘述被執行 特化的例外型別需放在較前的 catch 敘述內 20 10

Call Stack 機制 方法之間的呼叫是依循呼叫堆疊機制 (Call Stack Mechanism) a() b() 在 main() 內呼叫 a() 在 a() 內呼叫 b() a() main() main() main() b() a() b() a() b() 結束回到 a() a() a() 結束回到 main() main() main() main() 21 Call Stack 機制 例外與呼叫堆疊機制 在 c() 發生例外 c() b() a() c() b() a() c() 無處理則結束將例外丟給 b() b() a() b() 無處理則結束將例外丟給 a() a() a() 無處理則結束將例外丟給 main() main() main() main() main() 22 11

不論有沒有例外發生,finally 區塊內的敘述皆會執行 try { // 例外測試區 } catch( 例外型別例外名 ) { // 例外處理區 } finally { // 鐵定執行區 } finally 區塊 23 finally 區塊 finally 區塊不會執行或不會完全執行 : 有其它例外在 finally 區塊中發生 在 try 或 catch 區塊使用 System.exit() 離開程式 未執行至 finally 區塊, 執行緒即進入結束狀態 (dead state) 24 12

Stack Unwinding Exception not caught in scope Method terminates Stack unwinding occurs Another attempt to catch exception 25 1 // Fig. 15.4: UsingExceptions.java 2 // Demonstration of stack unwinding. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 // call throwexception to demonstrate stack unwinding 8 try { 9 throwexception(); 10 } 11 12 // catch exception thrown in throwexception 13 catch ( Exception exception ) { 14 System.err.println( "Exception handled in main" ); 15 } 16 } 17 18 // throwexception throws exception that is not caught in this method 19 public static void throwexception() throws Exception 20 { 21 // throw an exception and catch it in main 22 try { 23 System.out.println( "Method throwexception" ); 24 throw new Exception(); // generate exception 25 } 26 UsingExceptions.ja va Line 9 Line 13 Line 19 Line 24 13

27 // catch is incorrect type, so Exception is not caught 28 catch ( RuntimeException runtimeexception ) { 29 System.err.println( 30 "Exception handled in method throwexception" ); 31 } 32 33 // finally clause always executes 34 finally { 35 System.err.println( "Finally is always executed" ); 36 } 37 38 } // end method throwexception 39 40 } // end class UsingExceptions UsingExceptions.ja va Method throwexception Finally is always executed Exception handled in main printstacktrace, getstacktrace and getmessage Throwable class Method printstacktrace Prints method call stack Method getstacktrace Obtains stack-trace information Method getmessage Returns descriptive string 28 14

以 throw 丟出例外物件 使用 throw 敘述在程式中丟出例外物件 throw 例外物件 ; 丟出一包含訊息的自訂例外物件 : throw new RuntimeException( 除數為零 ); throw new Exception( 找不到檔案 ); throw 所丟出的例外物件同樣可以使用 try-catch 敘述處理 29 throws 關鍵字 throws 關鍵字使用於方法或建構子定義的標頭, 用來指出例外發生時, 由方法 ( 或建構子 ) 丟出的例外型別 throws 之後可以接多個例外型別名, 表示方法執行過程中可能丟出屬於這些例外型別的物件 方法不可以使用 throw 丟出不包含在 throws 宣告的例外型別之物件 30 15

throws 關鍵字 發生 Checked Exception 時須遵守處理或宣告丟出法則 (The Handle or Declare Rule ): 不是以 try-catch-finally 敘述處理就是以 throws 宣告丟出 31 1 // Fig. 15.5: UsingExceptions.java 2 // Demonstrating getmessage and printstacktrace from class Exception. 3 public class UsingExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 method1(); // call method1 9 } 10 11 // catch Exceptions thrown from method1 12 catch ( Exception exception ) { 13 System.err.println( exception.getmessage() + "\n" ); 14 exception.printstacktrace(); 15 16 // obtain the stack-trace information 17 StackTraceElement[] traceelements = exception.getstacktrace(); 18 19 System.out.println( "\nstack trace from getstacktrace:" ); 20 System.out.println( "Class\t\tFile\t\t\tLine\tMethod" ); 21 22 // loop through traceelements to get exception description 23 for ( int i = 0; i < traceelements.length; i++ ) { 24 StackTraceElement currentelement = traceelements[ i ]; 25 System.out.print( currentelement.getclassname() + "\t" ); 26 System.out.print( currentelement.getfilename() + "\t" ); UsingExceptions.ja va Line 8 Lines 13-14 Lines 25-26 16

27 System.out.print( currentelement.getlinenumber() + "\t" ); 28 System.out.print( currentelement.getmethodname() + "\n" ); 29 30 } // end for statement 31 32 } // end catch 33 34 } // end method main 35 36 // call method2; throw exceptions back to main 37 public static void method1() throws Exception 38 { 39 method2(); 40 } 41 42 // call method3; throw exceptions back to method1 43 public static void method2() throws Exception 44 { 45 method3(); 46 } 47 48 // throw Exception back to method2 49 public static void method3() throws Exception 50 { 51 throw new Exception( "Exception thrown in method3" ); 52 } UsingExceptions.ja va Lines 27-28 Line 37 Line 39 Line 43 Line 45 Line 49 Line 51 53 54 } // end class Using Exceptions Exception thrown in method3 java.lang.exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:51) at UsingExceptions.method2(UsingExceptions.java:45) at UsingExceptions.method1(UsingExceptions.java:39) at UsingExceptions.main(UsingExceptions.java:8) UsingExceptions.ja va Stack trace from getstacktrace: Class File Line Method UsingExceptions UsingExceptions.java 51 method3 UsingExceptions UsingExceptions.java 45 method2 UsingExceptions UsingExceptions.java 39 method1 UsingExceptions UsingExceptions.java 8 main 17

Chained Exceptions Wraps existing exception in a new exception enables exception to maintain complete stacktrace 35 1 // Fig. 15.6: UsingChainedExceptions.java 2 // Demonstrating chained exceptions. 3 public class UsingChainedExceptions { 4 5 public static void main( String args[] ) 6 { 7 try { 8 method1(); // call method1 9 } 10 11 // catch Exceptions thrown from method1 12 catch ( Exception exception ) { 13 exception.printstacktrace(); 14 } 15 } 16 17 // call method2; throw exceptions back to main 18 public static void method1() throws Exception 19 { 20 try { 21 method2(); // call method2 22 } 23 24 // catch Exception thrown from method2 25 catch ( Exception exception ) { 26 throw new Exception( "Exception thrown in method1", exception ); UsingChainedExcept ions.java Line 8 Lines 12-14 Line 18 Line 21 Line 26 18

27 } 28 } 29 30 // call method3; throw exceptions back to method1 31 public static void method2() throws Exception 32 { 33 try { 34 method3(); // call method3 35 } 36 37 // catch Exception thrown from method3 38 catch ( Exception exception ) { 39 throw new Exception( "Exception thrown in method2", exception ); 40 } 41 } 42 43 // throw Exception back to method2 44 public static void method3() throws Exception 45 { 46 throw new Exception( "Exception thrown in method3" ); 47 } 48 49 } // end class Using Exceptions UsingChainedExcept ions.java Line 31 Line 34 Line 39 Line 46 java.lang.exception: Exception thrown in method1 at UsingChainedExceptions.method1(UsingChainedExceptions.java:26) at UsingChainedExceptions.main(UsingChainedExceptions.java:8) Caused by: java.lang.exception: Exception thrown in method2 at UsingChainedExceptions.method2(UsingChainedExceptions.java:39) at UsingChainedExceptions.method1(UsingChainedExceptions.java:21)... 1 more Caused by: java.lang.exception: Exception thrown in method3 at UsingChainedExceptions.method3(UsingChainedExceptions.java:46) at UsingChainedExceptions.method2(UsingChainedExceptions.java:34)... 2 more UsingChainedExcept ions.java 19

Declaring New Exception Types Extend existing exception class Constructors and Exception Handling Throw exception if constructor causes error 39 Assertion 斷言 (Assertion) 是 J2SE 1.4 新增的功能, 其目的是為了方便程式的除錯 斷言的用處是在於去除邏輯上的錯誤 40 20

第一種斷言的宣告語法 : assert 布林運算式 ; 斷言的宣告 布林運算式的運算結果必須為布林值, 否則在程式編譯時會發生錯誤 布林運算式的結果若為 false, 則斷言將丟出一個沒有任何錯誤訊息的 AssertionError 物件 AssertionError 類別屬於 java.lang 套件, 為 Error 類別的子類別 41 斷言的宣告 第二種斷言的宣告語法 : assert 布林運算式 : 訊息運算式 ; 布林運算式為 false 時, 會丟出 AssertionError 物件 AssertionError 物件所包含的錯誤訊息是由訊息運算式所構成 訊息運算式結果通常為 String 物件, 其運算結果不可以是 void( 回傳型別為 void 的方法 ) 42 21

啟動斷言功能 斷言是 J2SE 1.4 新增的功能, 所以程式裡包含斷言敘述時, 必須使用 1.4 以上的編譯器版本編譯 使用 -source 參數指明編譯出來的 bytecode 為 1.4 版 : C:\>javac source 1.4 FileName.java 43 啟動斷言功能 執行時, 使用 -enableassertions 或 -ea 參數, 指明啟動斷言功能 : C:\>java -ea FileName 沒有使用 -enableassertions 或 -ea 啟動斷言功能, 則程式中的斷言敘述會被解譯器忽略 一般只有在程式測試時 ( 軟體開發過程 ), 才會開啟斷言功能 44 22

資源回收者 Garbage Collector 在程式一開始執行時就會監視 (trace) 每一個變數和物件實體, 當物件實體不被參考時, 此物件實體即成為 Unreachable Object JVM 你的程式變數 Garbage Collector 物件實體一 物件實體二 45 資源回收者 當物件不再被參照變數 (reference variable) 參考 (refer) 時, 它就會被認為是不再使用的 garbage Double d = new Double(0.5); d = new Double(0.2); d = null; 46 23

資源回收者 Double d = new Double(0.5); d = new Double(0.2); d = null; d Double 物件值 :0.5 d Double 物件值 :0.5 d null Double 物件值 :0.5 Double 物件值 :0.2 Double 物件值 :0.2 47 資源回收者 Unreachable Object 佔用的資源並不一定馬上就會被釋放 資源釋放和執行環境 ( 可用記憶體多寡,CPU 繁忙程度等 ) 有關, 程式設計者無法預測或決定資源何時被釋放 執行資源回收的動作只能被建議, 程式設計者無法強迫 (force) 資源回收的執行 48 24

finalize() 方法 Garbage Collection 機制在終結物件並釋放記憶體之前, 會先呼叫物件中的 finalize() 方法 finalize() 方法定義於 Object 類別, 不過為空方法, 主要是讓延伸類別覆蓋之用 protected void finalize()throws Throwable finalize() 方法不提供多載的功能 而且 finalize() 不接受傳入參數及回傳值, 所以一律以 void 定義, 並且無參數 49 25