共計 584 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,throw 關(guān)鍵字用于手動拋出一個異常。它通常用于方法中,當發(fā)生某種錯誤或條件不滿足時,程序員可以使用 throw 關(guān)鍵字來拋出一個異常。
使用 throw 關(guān)鍵字的語法如下:
throw exception;
其中,exception 是要拋出的異常對象,可以是 Java 內(nèi)置的異常類,也可以是自定義的異常類。
下面是一個使用 throw 關(guān)鍵字拋出異常的示例代碼:
public class Example {public static void main(String[] args) {
try {int result = divide(10, 0);
System.out.println("結(jié)果:" + result);
}
catch (ArithmeticException e) {System.out.println("發(fā)生異常:" + e.getMessage());
}
}
public static int divide(int a, int b) {if (b == 0) {throw new ArithmeticException("除數(shù)不能為零");
}
return a / b;
}
}
在上面的代碼中,divide 方法中使用 throw 關(guān)鍵字拋出一個 ArithmeticException 異常,如果參數(shù) b 為 0,就會拋出該異常。在 main 方法中,我們使用 try-catch 語句捕獲這個異常,并打印出異常信息。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完