本日學習:
檔案處理補充
例外處理
拋出與接收例外
public class Ch24_1{
public static void main(String[] args){
int a = 4, b = 0;
try{
if(b == 0)
throw new ArithmeticException();
else
System.out.println(a + "/" + b + "/" + "=" + a/b)
}
catch(ArithmeticException e){
System.out.println(e + " throwed");
}
}
}
throw new ArithmeticException(); 不一定要寫,沒寫系統也會自動拋出
2. 由函數拋出例外:未使用 try/catch/finally 時
- 函數名稱(引數 ......) throws 例外類別1, 例外類別2, ......{函數內的程式碼;}
- 使用 throws 指定函數拋出例外
- 例如:
public class Ch24_2{
public static void aaa(int a, int b) throws ArithmeticException{
int c;
c = a / b;
System.out.println(c);
}
public static void main(String[] args){
try{
aaa(4, 0);
}
catch(ArithmeticException e){
System.out.println(e + " throwed");
}
}
}