1 package p1.exception;
2
3
4 /*
5 * 老师用电脑上课。
6 *
7 * 问题领域中涉及两个对象。
8 * 老师,电脑。
9 *
10 * 分析其中的问题。
11 * 比如电脑蓝屏。冒烟。
12 *
13 */
14
15 class LanPingException extends Exception{
16 public LanPingException(String msg) {
17 super(msg);
18 // TODO Auto-generated constructor stub
19 }
20 }
21 class MaoYanException extends Exception{
22 public MaoYanException(String msg) {
23 super(msg);
24 // TODO Auto-generated constructor stub
25 }
26 }
27 class NoPlanException extends Exception{
28 public NoPlanException(String msg) {
29 super(msg);
30 // TODO Auto-generated constructor stub
31 }
32 }
33 class Computer{
34 private int state = 2;
35
36 public void run() throws LanPingException,MaoYanException{
37 if (state == 1) {
38 throw new LanPingException("电脑蓝屏");
39 }
40 if (state == 2) {
41 throw new MaoYanException("电脑冒烟");
42 }
43 System.out.println("电脑运行");
44 }
45 public void reset() {
46 state = 0;
47 System.out.println("电脑重启");
48 }
49 }
50 class Teacher{
51 private String name;
52 private Computer comp;
53 public Teacher(String name) {
54 this.name = name;
55 comp = new Computer();
56 // TODO Auto-generated constructor stub
57 }
58 public void prelect() throws NoPlanException{
59 try {
60 comp.run();
61 System.out.println(name+"讲课");
62 } catch (LanPingException e) {
63 System.out.println(e.toString());
64 comp.reset();
65 prelect();
66
67 } catch (MaoYanException e) {
68
69 System.out.println(e.toString());
70 test();
71 //可以对电脑进行维修,
72 // throw e;//做练习但没有解决冒烟问题抛出给别人
73 throw new NoPlanException("课时进度无法完成,原因:"+e.getMessage());
74
75 }
76
77
78 }
79 public void test() {
80 System.out.println("大家练习");
81 }
82 }
83 public class ExceptionTest {
84
85 public static void main(String[] args) {
86 // TODO Auto-generated method stub
87 Teacher t = new Teacher("武老师");
88 try {
89 t.prelect();
90 } catch (NoPlanException e) {
91 System.out.println(e.toString()+"……");
92 System.out.println("换人");
93 }
94
95 }
96
97 }
98
99 /*
100 * class NoAddException extends Exception{
101 *
102 * }
103 *
104 *
105 * void addData(Data d) throws NoAddException{
106 *
107 * 连接数据库
108 * try{
109 * 添加数据。出现异常 SQLException();
110 * }catche (SQLException e) {
111 * //处理代码
112 *
113 * thorw new NoAddException(); 内部处理了异常对外进行异常的转换,也叫异常的封装
114 * 不该暴露出的问题就不暴露,你暴露了对方也不能处理
115 *
116 * }finally{
117 * 关闭数据库
118 * }
119 *
120 *
121 *
122 *
123 */
124 * }
ExceptionTest
手机扫一扫
移动阅读更方便
你可能感兴趣的文章