1.自定义异常类
/**
* 蓝屏异常
*/
public class LanPingException extends Exception{
LanPingException(String msg){
super(msg);
}
}
/**
* 冒烟异常类
*/
public class MaoYanException extends Exception{
MaoYanException(String msg){
super(msg);
}
}
/**
* 课程无法完成异常类
*/
public class NoPlanException extends Exception{
NoPlanException(String msg){
super(msg);
}
}
2.创建类并抛出异常
/**
* 电脑类
*/
public class Computer {
private int state = 2;
public void run() throws LanPingException, MaoYanException{
if(state == 1){
throw new LanPingException("蓝屏了");
}
if(state == 2){
throw new MaoYanException("冒烟了");
}
System.out.println("电脑运行");
}
public void reset(){
this.state = 0;
System.out.println("电脑重启");
}
}
/**
* 老师类
*/
public class Teacher {
private String name;
private Computer comp;
Teacher(String name){
this.name = name;
comp = new Computer();
}
public void prelect() throws NoPlanException{
try {
comp.run();
System.out.println(this.name + "讲课");
} catch (LanPingException e){
System.out.println(e.toString());
comp.reset();
this.prelect();
} catch (MaoYanException e){
System.out.println(e.toString());
this.test();
throw new NoPlanException("课程进度无法完成,原因:" + e.getMessage());
}
}
public void test(){
System.out.println("学生们练习吧");
}
}
3.使用类并处理异常
public class ExceptionTest {
public static void main(String[] args) {
Teacher t = new Teacher("马云");
try {
t.prelect();
}catch (NoPlanException e) {
System.out.println("...." + e.toString());
System.out.println("换人");
}
}
}