Java异常抛出及try,catch应用实例

 1 class lanpingException extends Exception
 2 {
 3     lanpingException(String msg)
 4     {
 5         super(msg);
 6     }
 7 }
 8 
 9 class maoyanException extends Exception
10 {
11     maoyanException(String msg)
12     {
13         super(msg);
14     }
15 }
16 
17 class Computer
18 {
19     private int state=2;
20     public void run()throws lanpingException,maoyanException
21     {
22         if(state==1)
23         {
24             throw new lanpingException("lanping!!!");
25         }
26         if(state==2)
27         {
28             throw new maoyanException("maoyan!!!");
29         }
30         System.out.println("run bat");
31     }
32     public void reset()
33     {
34         state=0;
35         System.out.println("computer reset!");
36     }
37 }
38 
39 class Teacher
40 {
41     private String name;
42     private Computer comp;
43     Teacher(String name)
44     {
45         this.name=name;
46         comp=new Computer();
47     }
48     public void prelect()throws maoyanException
49     {
50         try
51         {
52             comp.run();
53             System.out.println(name+" speak");
54         }
55         catch(lanpingException e)
56         {
57             System.out.println(e.toString());
58             comp.reset();
59             prelect();
60         }
61         catch(maoyanException e)
62         {
63             System.out.println(e.toString());
64             test();
65             throw e;
66         }
67     }
68     public void test()
69     {
70         System.out.println("test yourself!");
71     }
72 }
73 
74 class Kandra
75 {
76     public static void main(String[] args)
77     {
78         Teacher pp=new Teacher("cao");
79         try
80         {
81             pp.prelect();
82             
83         }
84         catch(maoyanException e)
85         {
86             System.out.println("......");
87         }
88     }
89 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券