本帖最後由 tonyh 於 2017-3-25 11:32 編輯
利用 try...catch 語法捕捉例外, 與 toString() 函式將捕捉到的例外類別顯示出來.
try...catch 語法基本架構如下:
try
{
預期可能發生例外的敘述
}
catch(例外物件)
{
對應的處理程序
}
finally //可有可無
{
無論例外是否發生都會處理的程序
}

 - import java.util.Scanner;
- public class Ch51
- {
- public static void main(String args[])
- {
- while(true)
- {
- try
- {
- int x,y;
- Scanner s=new Scanner(System.in);
- System.out.print("請輸入分子: ");
- x=s.nextInt();
- System.out.print("請輸入分母: ");
- y=s.nextInt();
- System.out.println(x+"/"+y+" = "+x/y);
- System.out.println();
- }catch(Exception e)
- {
- System.out.println("程式發生錯誤!");
- System.out.println("例外類別: "+e.toString());
- System.out.println();
- }
- }
- }
- }
複製代碼 |