Java 的資料型別與例外狀況
Jim White
Java Developer
Exception,並寫程式碼解決問題throws,把例外傳回呼叫端方法throws 後用逗號列出多個例外型別public static void someMethod() throws IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException {
// method code
}
一般用 try-catch 處理 Exception
public static void main(String[] args) {
someMethod();
}
public static void someMethod(){
try {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
} catch (IndexOutOfBoundsException e) {
System.out.println(
"Oops - trying to get non-existent item");
}
}
用 throws 處理 Exception
public static void main(String[] args) {
try {
someMethod();
} catch (IndexOutOfBoundsException e) {
System.out.println(
"someMethod tried to get non-existent item");
}
}
public static void someMethod()
throws IndexOutOfBoundsException {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
}

Exception 可以被「再拋出(rethrow)」main 再拋出會讓應用程式停止
public class RethrowExample {
public static void main(String[] args) {
try {
method1(0);
} catch (ArithmeticException e) {
System.out.println("Oops - tried a bad quotient");
}
}
public static void method1(int divisor) throws ArithmeticException {
method2(divisor);
}
public static void method2 (int divisor) throws ArithmeticException {
int z = 5/divisor;
System.out.println(z);
}
}
Java 的資料型別與例外狀況