例外處理 (Exception)

7
1 例例例例 (Exception) 例例例例例例例 例例例例例例 例例例例

description

例外處理 (Exception). 例外處理的時機 例外處理語法 程式範例. 例外處理的使用時機. 程式有可能發生 『 可處理的錯誤 』 。 該錯誤不會影響程式中斷,處理之後仍可繼續執行。 例如: 使用者輸入字串資料進行加總。 陣列索引值超出範圍。 讀寫檔案時,檔案不存在。. 例外處理的語法. 例外處理是由  try 、 catch 與 finally 所組成的程式區塊,其語法如下:. 例外處理的語法. try { // 要檢查的程式敘述 ; } catch ( 例外類別 變數名稱 ) { - PowerPoint PPT Presentation

Transcript of 例外處理 (Exception)

Page 1: 例外處理 (Exception)

1

例外處理 (Exception)

例外處理的時機例外處理語法程式範例

Page 2: 例外處理 (Exception)

例外處理的使用時機程式有可能發生『可處理的錯誤』。該錯誤不會影響程式中斷,處理之後仍可繼續執行。

例如: 使用者輸入字串資料進行加總。 陣列索引值超出範圍。 讀寫檔案時,檔案不存在。

2

Page 3: 例外處理 (Exception)

3

例外處理的語法 例外處理是由  try、 catch與 finally所組成的程式區塊,其語法如下:

try { // 要檢查的程式敘述 ; } catch(例外類別 變數名稱 ) { // 例外發生時的處理敘述 ; } finally { // 一定會執行的程式碼 ; }

例外處理的語法

try區塊

catch區塊

finally區塊 (可加可不加 )

Page 4: 例外處理 (Exception)

使用者有可能會輸入錯誤的資料

範例使用者輸入數字進行加總 Scanner sc = new Scanner(System.in);

int sum=0;

System.out.print("請輸入 2個數字 :");

sum= sc.nextInt()+sc.nextInt();

System.out.println("sum=" + sum);

4

Page 5: 例外處理 (Exception)

當運算錯誤產生時

範例加入例外處理機制

Scanner sc = new Scanner(System.in);

int sum=0;

System.out.print("請輸入 2個數字 :");

try{

sum= sc.nextInt()+sc.nextInt();

}catch(Exception e){

System.out.println("例外 " + e + "產生 !");

}

5

Page 6: 例外處理 (Exception)

範例最後都要印出加總,可放在 finally中。

Scanner sc = new Scanner(System.in);

int sum=0;

System.out.print("請輸入 2個數字 :");

try{

sum= sc.nextInt()+sc.nextInt();

}catch(Exception e){

System.out.println("例外 " + e + "產生 !");

}finally{

System.out.println("sum=" + sum);

} 6

Page 7: 例外處理 (Exception)

練習讓使用者輸入 4個變數,輸出每個變數的值。若為數字則進行加總並印出結果。

7