自定义异常类举例
- 使用自定义的异常类
- 老师用电脑上课
- 老师发生上课异常
- 上课时电脑发生蓝屏或者冒烟异常
public class Demo {
public static void main(String[] args) {
Teacher1 teacher1 = new Teacher1(new Computer());
try {
teacher1.work();
}catch (ClassingException e) {
e.printStackTrace();
System.out.println("去修电脑");
}
}
}
class ClassingException extends Exception{
public ClassingException() {}
public ClassingException(String message) {
super(message);
}
}
class LanPingException extends Exception{
public LanPingException() {
}
public LanPingException(String message) {
super(message);
}
}
class MaoYanException extends Exception{
public MaoYanException() {
}
public MaoYanException(String message) {
super(message);
}
}
class Teacher1 {
Computer computer;
public Teacher1(Computer computer) {
this.computer = computer;
}
public void work() throws ClassingException
{
try {
computer.computerWork();
} catch (LanPingException e) {
e.printStackTrace();
computer.reset();
} catch (MaoYanException e) {
e.printStackTrace();
throw new ClassingException("老师无法继续上课");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Computer{
int status = 2;
public void reset(){
System.out.println("重启电脑");
}
public void computerWork() throws LanPingException,MaoYanException
{
switch (status) {
case 1:
throw new LanPingException("电脑蓝屏了");
case 2:
throw new MaoYanException("电脑冒烟了");
default:
break;
}
}
}
class BadComputer extends Computer{
public void computerWork() throws LanPingException, MaoYanException {
}
}