1 / 7

例外處理 (Exception)

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

ford
Download Presentation

例外處理 (Exception)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 例外處理(Exception) 例外處理的時機 例外處理語法 程式範例

  2. 例外處理的使用時機 • 程式有可能發生『可處理的錯誤』。 • 該錯誤不會影響程式中斷,處理之後仍可繼續執行。 • 例如: • 使用者輸入字串資料進行加總。 • 陣列索引值超出範圍。 • 讀寫檔案時,檔案不存在。

  3. 例外處理的語法 • 例外處理是由 try、catch與finally所組成的程式區塊,其語法如下: 例外處理的語法 try { // 要檢查的程式敘述; } catch(例外類別 變數名稱) { // 例外發生時的處理敘述; } finally { // 一定會執行的程式碼; } try區塊 catch區塊 finally區塊(可加可不加)

  4. 範例 • 使用者輸入數字進行加總 Scanner sc = new Scanner(System.in); int sum=0; System.out.print("請輸入2個數字:"); sum= sc.nextInt()+sc.nextInt(); System.out.println("sum=" + sum); 使用者有可能會輸入錯誤的資料

  5. 範例 • 加入例外處理機制 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 + "產生!"); } 當運算錯誤產生時

  6. 範例 • 最後都要印出加總,可放在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); }

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

More Related