class Throw1Demo {
public static void main(String[] args) {
int a = 1;
int b = 0;
if (b == 0) {
throw new ArithmeticException();
}
System.out.println(a / b);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:Throw1Demo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

第 7 行
throw new ArithmeticException();
這裡利用 ArithmeticException 類別 (class) 的建構子 (constructor) ,新建一個 ArithmeticException 型態的物件 (object) ,然後以 throw 丟出。
由於例外發生後,程式便會中斷執行,因此我們可以利用 try-catch 將 throw 的部份圍起來,好處理例外發生後的情況,例如
class Throw2Demo {
public static void main(String[] args) {
try {
int a = 1;
int b = 0;
if (b == 0) {
throw new ArithmeticException();
}
System.out.println(a / b);
}
catch (ArithmeticException ex) {
System.out.println("因為發生算術錯誤,所以程式印出這個訊息...");
}
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:Throw2Demo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

| 中英文術語對照 | |
|---|---|
| 關鍵字 | keyword |
| 陳述 | statement |
| 例外 | exception |
| 類別 | class |
| 建構子 | constructor |
| 物件 | object |
沒有留言:
張貼留言