异常处理实践

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("换人");
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值