Java程式錯誤分為Error和Exception,通常不處理Error,只對Exception作處理。
範例一: 帶有錯誤的java程式碼
import java.io.*;
public class ReadInput2 {
public static void main(String[] args) {
int no1 = input("請輸入分子");
int no2 = input("請輸入分母");
System.out.println(no1+"/"+no2+"="+(no1/no2));
}
public static int input(String message) {
System.out.println(message);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(in.readLine());
return a;
}
}
錯誤訊息是: Unreported IOException
方法一: 直接加try, catch 解決問題
import java.io.*;
public class ReadInput1 {
public static void main(String[] args) {
int no1 = input("請輸入分子");
int no2 = input("請輸入分母");
try {
System.out.println(no1 + "/" + no2 + "=" + (no1 / no2));
} catch (ArithmeticException e) {
System.out.print("分母錯誤!");
System.exit(0);
}
}
public static int input(String message) {
System.out.println(message);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int a = 0;
try {
a = Integer.parseInt(in.readLine());
} catch (IOException e) {
System.out.print("鍵盤讀取錯誤!");
System.exit(0);
} catch (NumberFormatException e) {
System.out.print("數字格式錯誤!");
System.exit(0);
}
return a;
}
}
方法二: 用throw 將錯誤處理的權限下放給呼叫本method的人
import java.io.*;
public class ReadInput2 {
public static void main(String[] args) throws IOException, NumberFormatException {
int no1 = input("請輸入分子");
int no2 = input("請輸入分母");
System.out.println(no1+"/"+no2+"="+(no1/no2));
}
public static int input(String message) throws IOException, NumberFormatException {
System.out.println(message);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(in.readLine());
return a;
}
}
也可以extend Exception來將自己的method定義為應檢核項目
範例二: 帶有錯誤的java程式碼
Bank() {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Bank");
stmt=conn.createStatement();
}
方法一: Surround Block with try-catch
Bank() {
try { //需將所有的程式碼放在同一個try, 因為第一個ClassNotFoundException 若產生,後面一定不可能連線成功,所以不適合分別try catch
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Bank");
stmt=conn.createStatement();
} catch (ClassNotFoundException ex) { //最後加上相應的catch clause
System.out.print("Error!");
} catch (SQLException ex) {
System.out.print("Error!");
}
}
方法二: throw Exception
Bank() throws Exception { //搞定
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Bank");
stmt=conn.createStatement();
}
Finally 使用時機: 關閉資源
不論try catch有沒有找到exception, 只要之前沒有System.exit(0); 就一定會執行finally.
在Java7,有一種AutoCloseable 寫法,只要在try之後{}之前加入小括弧(),(其中的內容只要有實做java.lang.AutoCloseable),該"資源"就可以自動被關閉。
多重Catch Catching Multiple Exception
try{
} catch (ClassNotFoundException | IOException){ //用|號分開
}