返回列表 發帖

例外處理 (三)

本帖最後由 tonyh 於 2015-1-10 18:10 編輯

利用 try...catch 語法捕捉例外, 針對不同的例外做出不同的回應, 並只允許使用者至多三次的錯誤嘗試.

  1. import java.util.*;
  2. public class ch52
  3. {
  4.     public static void main(String args[])
  5.     {
  6.          for(int i=1; i<=3; i++)
  7.          {
  8.              try
  9.              {
  10.                  Scanner s=new Scanner(System.in);
  11.                  int a, b;
  12.                  System.out.print("請輸入分子: ");
  13.                  a=s.nextInt();
  14.                  System.out.print("請輸入分母: ");
  15.                  b=s.nextInt();
  16.                  System.out.println(a+"/"+b+"="+(a/b));
  17.                  return;
  18.              }
  19.              catch(ArithmeticException e)
  20.              {
  21.                  System.out.println("運算錯誤! 分母不可為零!");
  22.              }
  23.              catch(InputMismatchException e)
  24.              {
  25.                  System.out.println("格式錯誤! 輸入須為整數!");
  26.              }
  27.              if(i==3)
  28.                  System.out.println("錯誤嘗試過多! 程式跳出!");
  29.              System.out.println();
  30.          }
  31.     }
  32. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

回復 5# 劉得恩
  1. #include<iostream>
  2. #include<exception>
  3. using namespace std;
  4. struct ooops : std::exception  //定義一個結構繼承std的exception(標準的例外處理類)
  5. {
  6.     const char* what() const throw() {return "Ooops!\n";}  //定義一個回傳 “Ooops”的函式來覆寫std的exception的what方法
  7. };
  8. void print(exception &ex)  //定義一個函示接收exception類的物件的位址傳入
  9. {
  10.     cout<<ex.what();  //並輸出該物件的what方法
  11. }
  12. int main()
  13. {
  14.     ooops e;   //宣告一個e(屬於ooops類)
  15.     //宣告一個p指標(屬於exception類)指向e的位置(父類指標指向子類物件位置是可以的,因為子類可以casting成為父類)
  16.     std::exception* p = &e;  
  17.     cout<<p->what();  //呼叫p的what方法,會輸出Ooops!\n,因為物件導向的 “多型”
  18.     try
  19.     {
  20.         print(*p);   //透過print函式呼叫p的what方法,會輸出Ooops!\n,因為物件導向的 “多型”
  21.         throw *p;   //丟出例外
  22.     }
  23.     catch(exception &ex)  //捕捉例外,這時候捕捉到的是exception標準例外
  24.     {
  25.         cout<<ex.what();  //輸出std::exception,標準exception的what()方法的輸出
  26.     }
  27.     //建議加上下面的程式:
  28.     try
  29.     {
  30.         throw e;  //丟出例外
  31.     }
  32.     catch(ooops &ex) //捕捉例外,這時候捕捉到的是ooops自定義的例外
  33.     {
  34.         cout<<ex.what();  //輸出Ooops!\n,自己寫的ooops的what()方法的輸出
  35.     }
  36.     //可以用來示範丟出ooops例外的結果
  37.     system("pause");
  38. }
複製代碼

TOP

返回列表