throw拋出異常的方式比較直接:
if(age < 0){throw new MyException("年齡不能為負數!");}來看一個例子:
package Test; public class Test2 { public static void main(String[] args) { String s = "abc"; if(s.equals("abc")) { throw new NumberFormatException(); } else { System.out. println(s); } } }運行結果如下:
java中可以對一個方法在定義時就進行異常的聲明,而後在實現時可以利用throw具體的拋出異常。
ppublic class Shoot { 創建類static void pop() throws NegativeArraySizeException { //定義方法並拋出NegativeArraySizeException異常int [] arr = new int[-3];//創建數組} public static void main(String[] args) {//主方法try { pop(); //調用pop()方法} catch (NegativeArraySizeException e) { System.out.println("pop()方法拋出的異常");//輸出異常信息}} }