廢話不多說了,直接給大家貼代碼了,具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
/*下面做了歸納總結(jié),歡迎批評指正*/ class ChushulingException extends Exception { public ChushulingException(String msg) { super(msg); } } class ChushufuException extends Exception { public ChushufuException(String msg) { super(msg); } } /*自定義異常 End*/ class Numbertest { public int shang(int x,int y) throws ChushulingException,ChushufuException { if(y<0) { throw new ChushufuException("您輸入的是"+y+",規(guī)定除數(shù)不能為負(fù)數(shù)!");//拋出異常 } if(y==0) { throw new ChushulingException("您輸入的是"+y+",除數(shù)不能為0!"); } int m=x/y; return m; } } class Rt001 { public static void main(String[]args) { Numbertest n=new Numbertest(); //捕獲異常 try { System.out.println("商="+n.shang(1,-3)); } catch(ChushulingException yc) { System.out.println(yc.getMessage()); yc.printStackTrace(); } catch(ChushufuException yx) { System.out.println(yx.getMessage()); yx.printStackTrace(); } catch(Exception y) { System.out.println(y.getMessage()); y.printStackTrace(); } finally{ System.out.println("finally!");} ////finally不管發(fā)沒發(fā)生異常都會被執(zhí)行 } } /* [總結(jié)] 1.自定義異常: class 異常類名 extends Exception { public 異常類名(String msg) { super(msg); } } 2.標(biāo)識可能拋出的異常: throws 異常類名1,異常類名2 3.捕獲異常: try{} catch(異常類名 y){} catch(異常類名 y){} 4.方法解釋 getMessage() //輸出異常的信息 printStackTrace() //輸出導(dǎo)致異常更為詳細(xì)的信息 */ |
以上所述是小編給大家介紹的Java自定義異常_動力節(jié)點(diǎn)Java學(xué)院整理,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!