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

Posted Angel_Kitty

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于Java异常抛出及try,catch应用实例的主要内容,如果未能解决你的问题,请参考以下文章

JAVA中try catch捕获异常的问题

JAVA语言如何进行异常处理,关键字throws,throw,try,catch,finally分别代表啥意义在try块中抛出异常吗

java中异常抛出后代码还会继续执行吗

JAVA——异常Throwable抛出异常Throws异常处理try-catch制造异常Throw自定义异常类

java异常 throw和try-catch的关系

java中异常有时要自己try-catch,有时又throws。还有同时两种都进行。到底该怎么分析处理异常?