Exceptions try catch and finally try try statements

  • Slides: 48
Download presentation
Exceptions

Exceptions

try, catch and finally try 區塊 try { 建立例外處理的第一個步驟 statements 將可能發生例外的程式碼, 用 try 區塊包起來

try, catch and finally try 區塊 try { 建立例外處理的第一個步驟 statements 將可能發生例外的程式碼, 用 try 區塊包起來 } statements 可以包括多個合法 Java 敘述,如: Print. Writer out = null; try { out = new Print. Writer(new File. Writer("Out. File. txt")); for (int i=0; i<size; i++) out. println("Value at: " + i + " = “ + victor. element. At(i)); }

try, catch and finally catch 區塊 提供處理該 try 區塊的例外 catch 的參數:例外類別,該類 別必須是繼承自 Throwable 的

try, catch and finally catch 區塊 提供處理該 try 區塊的例外 catch 的參數:例外類別,該類 別必須是繼承自 Throwable 的 subclass 回復錯誤、提醒使用者、結束程 式執行 try { … } catch (例外類別 變數名稱) { … }… try { … } catch (Array. Index. Out. Of. Bounds. Exception e) { System. err. println("Caught Array. Index. Out. Of. Bounds. Exception: "+ e. get. Message()); } catch (IOException e) { System. err. println( "Caught IOException: “ + e. get. Message()); }

try, catch and finally Exception. Demo 2. java public void write. List() { Print.

try, catch and finally Exception. Demo 2. java public void write. List() { Print. Writer out = null; try { out = new Print. Writer(new File. Writer("Out. File. txt")); for (int i=0; i<size; i++) out. println("Value at: " + i + " = “ + victor. element. At(i)); } catch (Array. Index. Out. Of. Bounds. Exception e) { System. err. println("Caught Array. Index. Out. Of. Bounds. Exception: " + e. get. Message()); } catch (IOException e) { System. err. println("Caught IOException: “ + e. get. Message()); } finally { if (out != null) { System. out. println("File has been closed!"); out. close(); } else { System. out. println("File has not been created!"); } } }

多重 catch Exception 繼承樹 Exception IOException Runtime. Exception Index. Out. Of. Bounds. Exception Array.

多重 catch Exception 繼承樹 Exception IOException Runtime. Exception Index. Out. Of. Bounds. Exception Array. Index. Out. Of. Bounds. Exception

throws method 將例外丟給 call stack 上層的 method 去處理 一個 method 利用 throws 將例外丟出 public

throws method 將例外丟給 call stack 上層的 method 去處理 一個 method 利用 throws 將例外丟出 public void write. List() throws IOException, Array. Index. Out. Of. Bounds. Exception { Print. Writer out = new Print. Writer(new. File. Writer("Out. File. txt")); for (int i=0; i<size; i++) out. println("Value at: " + i + " = " + victor. element. At(i)); out. close(); } Array. Index. Out. Of. Bounds. Exception 屬於執行時期例外,不 一定要丟出 public void write. List() throws IOException { … }

throw Example: Throw. Demo. java public class Throw. Demo { public static float method(float

throw Example: Throw. Demo. java public class Throw. Demo { public static float method(float x, float y) throws Arithmetic. Exception{ float result; if(y == 2){ throw new Arithmetic. Exception(); } result = x / y; return result; } public static void main (String[] args) { try { System. out. println(method(5, 2)); } catch (Arithmetic. Exception e) { System. out. println("Devide by 2! Please try again!"); e. print. Stack. Trace(); } } }

Throwable Class Java 將所有的例外 (Exception),通通定義成物件, 且全部是 “Throwable” 物件的子孫 java. lang. Object Throwable Error …

Throwable Class Java 將所有的例外 (Exception),通通定義成物件, 且全部是 “Throwable” 物件的子孫 java. lang. Object Throwable Error … … … Java VM Errors Exception … … … Runtime. Exception … … … Checked Exception Runtime Exception

Throwable Class 方法 解釋 String get. Message() 傳回錯誤訊息 void print. Stack. Trace() 印出 “錯誤處理呼叫鍊”

Throwable Class 方法 解釋 String get. Message() 傳回錯誤訊息 void print. Stack. Trace() 印出 “錯誤處理呼叫鍊” (Error Handling Calling Chain) 至標準錯誤設備 (System. err) void print. Stack. Trace (Print. Stream s) 印出 “錯誤處理呼叫鍊” 至指定的輸出設備 Throwable fill. In. Stack. Trace() 將此錯誤再度放回 Java VM 中,供他人繼續 使用 String to. String() 印出此 Throwable 物件的簡短描述

Your Own Exception Classes 假設: 自訂類別:Employees(); 自訂錯誤:薪水遞增函數每次不得超過公司規定之 5% Exception 名稱:Over. Salary. Raise. Exception

Your Own Exception Classes 假設: 自訂類別:Employees(); 自訂錯誤:薪水遞增函數每次不得超過公司規定之 5% Exception 名稱:Over. Salary. Raise. Exception

Your Own Exception Classes 由繼承樹來看,Over. Salary. Raise. Exception 最好的祖 先會是 Exception: java. lang. Object

Your Own Exception Classes 由繼承樹來看,Over. Salary. Raise. Exception 最好的祖 先會是 Exception: java. lang. Object Throwable Error Exception Over. Salary. Raise. Exception Runtime. Exception

Your Own Exception Classes 自訂例外事件通常包含兩個建構元: public 建構元名稱 () {} public 建構元名稱 (String s) {

Your Own Exception Classes 自訂例外事件通常包含兩個建構元: public 建構元名稱 () {} public 建構元名稱 (String s) { super(s); } 第二個建構元傳入之字串為錯誤訊息。即到時候用 get. Message() 傳回來 的字串。 class Over. Salary. Raise. Exception extends Exception { public Over. Salary. Raise. Exception() {} public Over. Salary. Raise. Exception(String s) { super(s); } }

Your Own Exception Classes Example: Over. Salary. Raise. Exception. java class Over. Salary. Raise.

Your Own Exception Classes Example: Over. Salary. Raise. Exception. java class Over. Salary. Raise. Exception extends Exception { public Over. Salary. Raise. Exception(){} public Over. Salary. Raise. Exception(String s) { super(s); } }

Multithread的生命週期 start() notify(), I/O unblock Blocked Runnable sleep(), wait(), , I/O block Running yield()

Multithread的生命週期 start() notify(), I/O unblock Blocked Runnable sleep(), wait(), , I/O block Running yield()

Thread類別 java. lang. Thread public class Thread extends Object implements Runnable 提供的基本方法 static yield()

Thread類別 java. lang. Thread public class Thread extends Object implements Runnable 提供的基本方法 static yield() 讓目前running的暫停, 讓runnable的擇一跑 static sleep() 讓目前running的睡一個設定的時間 start() 啟動, 之後JVM可啟動該thread的run() set. Priority() • set. Priority(MAX_PRIORITY):給最大優先權 • set. Priority(MIN_PRIORITY):給最小優先權 • set. Priority(NORM_PRIORITY):預設的優先權

如果執行緒間彼此有同步的考量 (My. Thread 3. java) public class My. Thread 3 implements Runnable{ static int

如果執行緒間彼此有同步的考量 (My. Thread 3. java) public class My. Thread 3 implements Runnable{ static int max=0; public void run() { for(int i = 1; i<=5000; i++) { int tmp=max; System. out. println( Thread. current. Thread(). get. Name() + " " + ++tmp ); max=tmp; } } } 各把max拿來加 5000次 最後卻不一定等於 10000 而且每次都不一樣, why? class Test. Thread 3 { public static void main(String args[]) { My. Thread 3 r = new My. Thread 3(); Thread t 1 = new Thread(r); Thread t 2 = new Thread(r); t 1. set. Name("t 1"); t 2. set. Name("t 2"); t 1. start(); t 2. start(); } }

方法加 synchronized public class My. Thread 4 implements Runnable{ static int max=0; public void

方法加 synchronized public class My. Thread 4 implements Runnable{ static int max=0; public void run() { for(int i = 1; i<=5000; i++) add. Max(); } private synchronized void add. Max() { int tmp=max; System. out. println(Thread. current. Thread(). get. Name() + " " + ++tmp); max=tmp; } 保證 } add. Max()這個方法 只有同時間只有一個 process可以執行

I/O Overview of I/O Streams Using the Streams File Streams Wrap Streams Input. Streams

I/O Overview of I/O Streams Using the Streams File Streams Wrap Streams Input. Streams Your Turn Standard in and out Streams Pipe Streams Sequence. Input. Stream Filter Streams Random Access File

Overview of I/O Streams Character Streams 用來處理 16 位元資料,如:字元資料(unicode) Reader 和 Writer 是所有 character

Overview of I/O Streams Character Streams 用來處理 16 位元資料,如:字元資料(unicode) Reader 和 Writer 是所有 character streams 的 abstract superclasses

Overview of I/O Streams Byte Streams 用來處理 8 位元資料,如:執行檔、圖檔和聲音檔 Input. Stream 和 Output. Stream

Overview of I/O Streams Byte Streams 用來處理 8 位元資料,如:執行檔、圖檔和聲音檔 Input. Stream 和 Output. Stream 是所有 byte streams 的 abstract superclasses

Overview of I/O Streams Understanding the IO Superclasses Reader 與 Input. Stream 有非常類似的 API,只是處理的資

Overview of I/O Streams Understanding the IO Superclasses Reader 與 Input. Stream 有非常類似的 API,只是處理的資 料型態不同,如: • Reader 中的 methods int read() int read(char cbuf[], int offset, int length) • Input. Stream 中的 methods int read() int read(byte buf[], int offset, int length)

Overview of I/O Streams Writer 與 Output. Stream • Writer 中的 methods int write(int

Overview of I/O Streams Writer 與 Output. Stream • Writer 中的 methods int write(int c) int write(char cbuf[], int offset, int length) • Output. Stream 中的 methods int write(int c) int write(byte buf[], int offset, int length) 所以的 Streams 都一樣,在物件建立之後,就會自動開啟, 而呼叫 close() 就可以關閉資料流

Using the Streams I/O 類型 資料流類別 說明 File. Reader File. Writer 功能在於存取檔案或檔 案系統的內容 檔案(File)

Using the Streams I/O 類型 資料流類別 說明 File. Reader File. Writer 功能在於存取檔案或檔 案系統的內容 檔案(File) File. Input. Stream File. Output. Stream Piped. Reader Piped. Writer 管線(Pipe) 將某個程式(或 Thread) 的輸出導入另一個程式 的輸入 Piped. Input. Stream Piped. Output. Stream 未提供 串接(Concatenate) Sequence. Input. Stream 將多個 input stream 串接 到同一個 input stream

Using the Streams I/O 類型 資料流類別 說明 Buffered. Reader Buffered. Writer 讀寫時為資料緩衝區, 可以減少存取原始資料 的次數

Using the Streams I/O 類型 資料流類別 說明 Buffered. Reader Buffered. Writer 讀寫時為資料緩衝區, 可以減少存取原始資料 的次數 緩衝(Buffer) Buffered. Input. Stream Buffered. Output. Stream Filter. Reader Filter. Writer 過濾(Filter) 這幾個類別都是 abstract class,定義了過濾讀寫 資料的介面 Filter. Input. Stream Filter. Output. Stream 未提供 物件序列化 (Object Serialization) Object. Input. Stream Object. Output. Stream 用來做物件序列化( Object Serialization)的 動作

File. Reader / File. Writer 可利用 File 物件來當作 File. Reader / File. Writer 的建

File. Reader / File. Writer 可利用 File 物件來當作 File. Reader / File. Writer 的建 構元參數 如: File input. File = new File(“test. txt”); File. Reader in = new File. Reader(input. File); 建立 File. Reader 的物件之後可用 read() 來讀入 16 -bit 字元 建立 File. Writer 的物件之後可用 write() 來寫出 16 -bit 字元

File. Reader / File. Writer Example: Copy. java … File input. File = new

File. Reader / File. Writer Example: Copy. java … File input. File = new File("farrago. txt"); File output. File = new File("outagain. txt"); File. Reader in = new File. Reader(input. File); File. Writer out = new File. Writer(output. File); int c; while ((c = in. read()) != -1) out. write(c); in. close(); out. close(); …

Java讀寫檔案 Buffered. Reader 和 Buffered. Writer 程式做 IO 動作時,使用 8 K 左右大小之 Buffer 可得到最佳效能

Java讀寫檔案 Buffered. Reader 和 Buffered. Writer 程式做 IO 動作時,使用 8 K 左右大小之 Buffer 可得到最佳效能 Buffered. Reader 和 Buffered. Writer 已經內建 Buffer 幫你做實際 IO 傳輸 buffer 處理 示範程式 • 使用 Buffered. Reader 讀出檔案內容

示範程式 Example: Buf. Reader. Demo. java String file = "farrago. txt"; File name =

示範程式 Example: Buf. Reader. Demo. java String file = "farrago. txt"; File name = new File(file); if ( name. exists() ) { Buffered. Reader input = new Buffered. Reader( new File. Reader(name)); String str; while ( (str = input. read. Line()) != null ) // 判別是否讀到檔尾 System. out. println(str); input. close(); } else System. out. println("File [" + name + "] doesn't exist. "); }

Buffered. Reader使用法 Constructor: Buffered. Reader(Reader in); Reader 是一個 abstract 類別,不能被 new 出來,只 能被繼承使用 查API可知道

Buffered. Reader使用法 Constructor: Buffered. Reader(Reader in); Reader 是一個 abstract 類別,不能被 new 出來,只 能被繼承使用 查API可知道 Reader 被 File. Reader 繼承。 而 File. Reader 有一 Constructor 為 File. Reader(String filename) 因此我們可以 new 一個 File. Reader,當作參數傳入 Buffered. Reader 之 Constructor

Buffered. Writer使用法 Constructor: Buffered. Writer(Writer out); Writer 是一個 abstract 類別,不能被 new 出來,只 能被繼承使用 查

Buffered. Writer使用法 Constructor: Buffered. Writer(Writer out); Writer 是一個 abstract 類別,不能被 new 出來,只 能被繼承使用 查 API 可知到 Writer 被 File. Writer 繼承。 而 File. Writer 有一 Constructor 為 File. Writer(String filename) 因此我們可以 new 一個 File. Writer,當作參數傳入 Buffered. Writer 之 Constructor

為何Java如此大費周章 使用Buffered. Reader為何還要先產生File. Reader,再 指向檔案名稱? Buffered. Reader br = new Buffered. Reader(new File. Reader(“Test.

為何Java如此大費周章 使用Buffered. Reader為何還要先產生File. Reader,再 指向檔案名稱? Buffered. Reader br = new Buffered. Reader(new File. Reader(“Test. txt”)); 因為 Buffered. Reader 和 Buffered. Writer 不只可以做檔案處 理之功能 只需置換 Buffered. Reader 之建構子,即可使用相同的API 做出讀取鍵盤輸入和網路傳輸等功能 請注意 Buffered. Reader 和 Buffered. Writer 的建構子 為 Reader 和 Writer 之類別

Input. Stream / Output. Stream 對於位元的檔案 IO,Java 程式是開啟 File. Output. Stream 和 File. Input.

Input. Stream / Output. Stream 對於位元的檔案 IO,Java 程式是開啟 File. Output. Stream 和 File. Input. Stream 串流,如: File. Output. Stream output = new File. Output. Stream(file); … File. Input. Stream input = new File. Input. Stream(name); … 參數可以是檔案路徑字串,或是 File 物件

Input. Stream / Output. Stream Example: In. Out. Stream. Demo. java File. Input. Stream

Input. Stream / Output. Stream Example: In. Out. Stream. Demo. java File. Input. Stream input = new File. Input. Stream(name); File. Output. Stream output = new File. Output. Stream("clone. jpg"); // 當讀取的檔案不是文字檔的話,用 File. Reader 來讀取會有問題 //File. Reader input = new File. Reader(name); //File. Writer output = new File. Writer("clone. jpg"); int b; while ( (b = input. read()) != -1 ) { output. write(b); System. out. println(b); // 顯示出一個 pixel 的數值 } output. close(); input. close();