如何自定义异常类

1. 如何自定义异常类?
① 继承于现有的异常体系。通常继承于RuntimeException \ Exception
② 通常提供几个重载的构造器
③ 提供一个全局常量,声明为:static final long serialVersionUID;

2. 如何使用自定义异常类?
> 在具体的代码中,满足指定条件的情况下,需要手动的使用"throw + 自定义异常类的对象"方式,将异常对象抛出。
> 如果自定义异常类是非运行时异常,则必须考虑如何处理此异常类的对象。(具体的:① try-catch-finally ② throws)
package chapter09_exception_teacher.src.com.atguigu04._throw;

/**
 * ClassName: BelowZeroException
 * Description:
 *
 * @Author 尚硅谷-宋红康
 * @Create 10:49
 * @Version 1.0
 */
public class BelowZeroException extends Exception{
    static final long serialVersionUID = -3387516999948L;
    public BelowZeroException(){

    }

    public BelowZeroException(String name){
        super(name);
    }

    public BelowZeroException(String message, Throwable cause) {
        super(message, cause);
    }
}

package chapter09_exception_teacher.src.com.atguigu04._throw;

/**
 * ClassName: ThrowTest
 * Description:
 *
 * @Author 尚硅谷-宋红康
 * @Create 10:27
 * @Version 1.0
 */
public class ThrowTest {
    public static void main(String[] args) {
        Student s1 = new Student();
        try{
            s1.regist(10);
            s1.regist(-10);
            System.out.println(s1);
        }catch(Exception e){
            e.printStackTrace();
//            System.out.println(e.getMessage());
        }



    }
}

class Student {
    int id;

//    public void regist(int id) t{
//        if(id > 0){
//            this.id = id;
//        }else{
            System.out.println("输入的id非法");
//            //手动抛出异常类的对象
            throw new RuntimeException("输入的id非法");
//
//        }
//    }

    public void regist(int id) throws Exception {
        if (id > 0) {
            this.id = id;
        } else {
//            System.out.println("输入的id非法");
            //手动抛出异常类的对象
//            throw new RuntimeException("输入的id非法");

//            throw new Exception("输入的id非法");

//            throw new String("输入的id非法"); //报错
            throw new BelowZeroException("输入的id非法");

//            System.out.println("此语句不能被执行");
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}

3. 为什么需要自定义异常类?
我们其实更关心的是,通过异常的名称就能直接判断此异常出现的原因。既然如此,我们就有必要在实际开发场景中,
不满足我们指定的条件时,指明我们自己特有的异常类。通过此异常类的名称,就能判断出具体出现的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值