[JAVA基础] 异常 为什么要自定义异常

假设我们有多个异常时,对每一个在主方法try——catch显得冗杂;

所以可以throw一个异常类,在测试中进行try——catch;

throw:手动抛出异常,捕获异常;

throws:异常处理的方式;

throws +异常类型,写在方法声明处。

解释:当方法被调用时,可能由(throw new +异常类型)来发出异常,代码出现异常时,将在代码异常处 生成一个异常对象,而这个异常对象一旦符合(throws +异常类型) 中异常类型的要求便会抛出异常。

如果抛出的异常对象继承的RuntimeException,那么调用的方法讲不需要再继承Exception。

为什么要自定义一个异常

public class Test{
    public static void main(String[] args) {
        try {
            cs c=new cs();
            c.Setcs("刘德华",-88);
            System.out.println(c.toString());
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}

 class cs {
    String name;
    int age;
      public void Setcs(String name, int age) throws RuntimeException{
        this.name=name;
        if (age>150||age<0)
            throw new CustomerEx("年龄输入错误");
        this.age=age;

    }
        @Override
     public String toString() {
         return "cs{" +
                 "name=" + name +  +
                 ", age=" + age +
                 };
     }

}

当我们这个文件中出现多个异常中,显然runtime便不能满足。

这个就是属于从业务角度以后去理解的,就比如说你看你处理一个文件是,你可能是网络异常,可能是数据库查询异常,可能是等等等等,就相当于细化的..

自定义异常类

①继承Exception或者RuntimeException(运行时异常,多用这个),

②提供一个无参构造器 和形参为Strting类型的构造器

定义一个类

进行测试

经验分享 程序员 微信小程序 职场和发展