class Throws1Demo {
public int divide(int a, int b) throws ArithmeticException {
return a / b;
}
public static void main(String[] args) {
Throws1Demo t = new Throws1Demo();
try {
System.out.println(t.divide(15, 20));
System.out.println(t.divide(10, 2));
System.out.println(t.divide(63, 9));
System.out.println(t.divide(2, 0));
}
catch (ArithmeticException ex) {
System.out.println("發生算術錯誤");
}
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:Throws1Demo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

第 2 行
public int divide(int a, int b) throws ArithmeticException {這裡 divide() 宣告丟出 ArithmeticException 的例外,因此呼叫 (call) divide() 的 main()
try {
System.out.println(t.divide(15, 20));
System.out.println(t.divide(10, 2));
System.out.println(t.divide(63, 9));
System.out.println(t.divide(2, 0));
}
catch (ArithmeticException ex) {
System.out.println("發生算術錯誤");
}有呼叫 divide() 的部份就必須放在 try-catch 陳述 (statement) 之中。
如果一個方法需要丟出多個例外,如擴充 divide() 的功能,使 divide() 除了有可能會發生 ArithmeticException 之外,也可能發生 IOException ,這時,多個例外類別 (class) 以逗點分開即可,如下
public int divide(int a, int b) throws IOException, ArithmeticException {
//方法的程式碼
}| 中英文術語對照 | |
|---|---|
| 方法 | method |
| 關鍵字 | keyword |
| 例外 | exception |
| 呼叫 | call |
| 陳述 | statement |
| 類別 | class |
沒有留言:
張貼留言