當方法未捕獲檢查性異常(Checked Exception)時,必須在方法簽名末尾使用 throws 關鍵字聲明可能拋出的異常類型。而 throw 則用於實際拋出一個異常實例(無論是新建還是剛捕獲的)。簡單區分:throw 是拋出動作,throws 是聲明將要拋出的異常類型。
import java.io.*;
public class ClassName {
public void deposit(double amount) throws RemoteException {
// 方法實現
throw new RemoteException();
}
// 類的其餘定義
}
多個異常之間以逗號分隔:
import java.io.*;
public class ClassName {
public void withdraw(double amount) throws RemoteException, InsufficientFundsException {
// 方法實現
}
}
finally 代碼塊緊跟在 try-catch 之後,無論是否發生異常,其中的代碼都會被執行。常用於資源釋放、清理等收尾工作。
try {
// 程序代碼
} catch (異常類型1 變量名1) {
// 處理代碼
} catch (異常類型2 變量名2) {
// 處理代碼
} finally {
// 無論如何都會執行的代碼
}
public class Test {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three: " + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown: " + e);
} finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
運行結果顯示捕獲到數組下標越界異常,但 finally 塊依然執行。
catch 不能獨立於 try 存在。try/catch 後添加 finally 並非強制。try 後不能既無 catch 也無 finally。try、catch、finally 之間不能插入其他代碼。Java 允許開發者自定義異常類,需遵循以下規則:
Throwable。Exception。RuntimeException。java.lang.Exception 聲明異常類。throw 拋出自定義異常實例。throws 聲明該異常。自定義異常類
class MyException extends Exception { }
業務異常類:InsufficientFundsException
import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
使用異常的業務類:CheckingAccount
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= balance) {
balance -= amount;
} else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() { return balance; }
public int getNumber() { return number; }
}
測試類:BankDemo
public class BankDemo {
public static void main(String[] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
編譯運行後,控制台輸出餘額不足的提示與堆棧信息。
NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException。IllegalArgumentException、IllegalStateException。try-catch。catch 後可加 catch(Exception) 兜底。try-catch。printStackTrace() 輸出,應具體處理。finally 釋放佔用資源。