Java是如何處理異常的?
Java異常處理是通過五個(gè)關(guān)鍵字來完成的:try
、catch
、finally
、throw
和throws
。
try
: 這個(gè)塊用來包裹可能會(huì)引發(fā)異常的代碼。catch
: 這個(gè)塊用來捕獲異常??梢杂卸鄠€(gè)catch塊來捕獲不同類型的異常。finally
: 這個(gè)塊無論是否捕獲到異常都會(huì)執(zhí)行。通常用于關(guān)閉資源等。throw
: 用于手動(dòng)拋出異常。throws
: 用在方法簽名中,表明這個(gè)方法可能會(huì)拋出的異常類型。
下面是一些簡(jiǎn)單的示例代碼,展示了異常處理的基本用法:
1. 使用 try-catch-finally
處理異常
public class ExceptionExample {
??? public static void main(String[] args) {
??????? try {
??????????? int result = 10 / 0; // 這將會(huì)引發(fā)一個(gè) ArithmeticException
??????? } catch (ArithmeticException e) {
??????????? System.out.println("捕獲到異常: " + e.getMessage());
??????? } finally {
??????????? System.out.println("無論是否捕獲到異常,這里的代碼都會(huì)執(zhí)行。");
??????? }
??? }
}
2. 拋出異常
你可以使用throw
關(guān)鍵字手動(dòng)拋出異常:
public void checkAge(int age) throws Exception {
??? if (age < 18) {
??????? throw new Exception("年齡小于18歲");
??? }
??? System.out.println("年齡合法");
}
以上代碼定義了一個(gè)方法,當(dāng)年齡小于18歲時(shí),它將拋出一個(gè)異常。
3. 方法簽名中的 throws
當(dāng)你的方法可能會(huì)拋出某種異常,但不想在該方法內(nèi)部處理它時(shí),你可以在方法簽名中使用throws
關(guān)鍵字:
public void readFile(String fileName) throws FileNotFoundException {
??? File file = new File(fileName);
??? FileReader reader = new FileReader(file);
??? // ...
}
在這個(gè)示例中,readFile
方法可能會(huì)拋出FileNotFoundException
,所以在調(diào)用該方法的地方必須處理這個(gè)異常。
這些示例代碼展示了Java異常處理的基本概念。如果你有任何更具體的問題或想要了解更復(fù)雜的示例,請(qǐng)隨時(shí)提問!