java异常处理练习

异常的练习:

老师用电脑上课。

开始思考上课中出现的问题。


比如问题是
    电脑蓝屏。
    电脑冒烟。

要对问题进行描述,封装成对象。


可是当冒烟发生后,出现讲课进度无法继续。

出现了讲师的问题:课时计划无法完成。

 

 1 class Teacher
 2 {
 3     private Computer cmp;
 4     public void shangKe()throws NoPlanException           /*声明异常*/
 5     {
 6         cmp=new Computer();
 7         try
 8         {
 9             cmp.run();
10         }
11         catch(LanPingException e)                             /*电脑捕获处理蓝屏的异常*/                                     
12         {
13             cmp.recst();
14         }
15         catch(MaoYanException e)                                /*电脑捕获处理电脑冒烟的异常*/
16         {
17             throw new NoPlanException("上课无法继续,因为"+e.getMessage());       /*电脑无法处理这个异常,继续把这个异常抛给老师来处理*/      
18         }
19         
20         System.out.println("老师上课");                                /*没有异常,老师就正常上课*/
21     }
22 }
23 class LanPingException extends Exception                             /*自定义蓝屏异常*/
24 {
25     LanPingException(String m)
26     {
27         super(m);
28     }
29 }
30 
31 class MaoYanException extends Exception                          /*自定义电脑冒烟异常*/
32 {
33     MaoYanException(String m)
34     {
35         super(m);
36     }
37 }
38 class NoPlanException extends Exception                          /*自定义老师处理异常*/
39 {
40     NoPlanException(String m)
41     {
42         super(m);
43     }
44 }
45 
46 class Computer
47 {
48     private int state=3;                      /*不同的异常状态选择*/
49     
50     public void run()throws LanPingException,MaoYanException
51     {
52         if(state==2)                                          
53         {
54             throw new LanPingException("电脑蓝屏了");                /*符合条件就抛出异常对象*/
55         }
56         if(state==3)
57         {
58             throw new MaoYanException("电脑冒烟了");
59         }
60         System.out.println("电脑运行");
61     }
62     
63     
64     public void recst()
65     {
66         System.out.println("电脑重启");
67     }
68 }
69 
70 class ExceptionText
71 {
72     public static void main(String args[])
73     {
74         Teacher t=new Teacher();
75         try
76         {
77             t.shangKe();
78         }
79         catch(NoPlanException e)                             /*老师捕获处理电脑冒烟异常*/      
80         {
81             System.out.println(e.toString());
82         }        
83     }
84 }

运行结果:

NoPlanException: 上课无法继续,因为电脑冒烟了

posted @ 2016-06-13 20:34  Qi_Yuan  阅读(816)  评论(0编辑  收藏  举报