throw拋出異常的方式比較直接:
1
2
3
|
if (age < 0 ){ throw new MyException( "年齡不能為負數!" ); } |
來看一個例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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具體的拋出異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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()方法拋出的異常" ); //輸出異常信息 } } } |