1、建立exception包,編寫TestException.java程序,主方法中有以下代碼,確定其中可能出現(xiàn)的異常,進(jìn)行捕獲處理。
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
|
public class YiChang { public static void main(String[] args){ for ( int i= 0 ;i< 4 ;i++){ int k; switch (i){ case 0 : int zero= 0 ; try { k= 911 /zero; } catch (ArithmeticException e){ System.out.println( "出現(xiàn)算數(shù)異常!" ); } break ; case 1 : try { int b[]= null ; k = b[ 0 ]; } catch (NullPointerException e){ System.out.println( "出現(xiàn)空指針異常!" ); } break ; case 2 : int c[]= new int [ 2 ]; try { k=c[ 9 ]; } catch (ArrayIndexOutOfBoundsException e){ System.out.println( "出現(xiàn)數(shù)組序號溢出!" ); } break ; case 3 : try { char ch= "abc" .charAt( 99 ); } catch (StringIndexOutOfBoundsException e){ System.out.println( "出現(xiàn)數(shù)據(jù)類型轉(zhuǎn)換異常!" ); } break ; } } } } |
2、建立exception包,建立Bank類,類中有變量double balance表示存款,Bank類的構(gòu)造方法能增加存款,Bank類中有取款的發(fā)方法withDrawal(double dAmount),當(dāng)取款的數(shù)額大于存款時(shí),拋出InsufficientFundsException,取款數(shù)額為負(fù)數(shù),拋出NagativeFundsException,如new Bank(100),表示存入銀行100元,當(dāng)用方法withdrawal(150),withdrawal(-15)時(shí)會拋出自定義異常。
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
|
public class InsufficientFundsException extends Exception { public String getMessage(){ return "您的余額不足!" ; } } public class NagativeFundsException extends Exception{ public String getMessage(){ return "取款金額不能為負(fù)數(shù)!" ; } } public class Bank { private static double balance; Bank(){ }; Bank( double balance){ this .balance=balance; } public static void withDrawal( double dAmount) throws InsufficientFundsException,NagativeFundsException{ if (dAmount>balance){ throw new InsufficientFundsException(); } if (dAmount< 0 ){ throw new NagativeFundsException(); } } public static void main(String[] args){ Bank b= new Bank( 100 ); System.out.println( "我有" +balance+ "元存款!" ); try { withDrawal( 150 ); } catch (InsufficientFundsException | NagativeFundsException e){ e.printStackTrace(); } try { withDrawal(- 15 ); } catch (NagativeFundsException |InsufficientFundsException e){ e.printStackTrace(); } } } |
一道關(guān)于一道關(guān)于java異常處理的題目就給大家介紹這么多,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時(shí)回復(fù)大家的,在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/jingzhenhua/p/5902377.html