异常

异常分类

exception

检查异常:开发代码时就提示的异常。

运行异常:运行时抛出的异常。

常见异常

异常名 说明
Exception 异常类的根类
---- ----
RuntimeException 运行时异常类的基类
---- ----
ArithmeticException 算术错误情形,如以零作除数
---- ----
ArrayIndexOutOfBoundExceptio 数组大小小于或大于实际的数组大小
---- ----
NullPointerException 尝试访问 null 对象成员
---- ----
ClassNotFoundException 不能加载所需的类
---- ----
NumberFormatException 数字转化格式异常,字符串到 float 转换无效
---- ----
IOException I/O 异常的根类
---- ----
FileNotFoundException 找不到文件
---- ----
SQLException 数据库访问异常
---- ----
InterruptedException 线程被中断异常
---- ----
Exception 异常类的根类

异常处理

捕获并处理异常

  • try - catch -finally
    语法:try必须存在,catch和finally至少有一个。
    多重catch处理多异常(标准)。先子类后父类原则。
    该用父类Exception(不专业)。
try {
  //可能产生异常的代码块
    Class.forName("");
} catch (ClassNotFoundException e) {
  //捕获异常并处理
    e.printStackTrace();//在控制台输出异常信息
}finally{
  //无论是否出现异常都执行的代码块(return)
}

声明异常

throws

public static void main(String[] args) throws ClassNotFoundException,IOException { 
   Class.forName("");
}

异常产生

自动抛出异常:JVM

手动抛出异常:throw (+ throws)

public void setAge(int age) throws Exception {
        if(age >= 20 || age < 0){
            throw new Exception("数据错误");
        }else{
            this.age = age;
        }
}

自定义异常

  • 继承父类Exception。
  • 定义错误信息。
  • 重写toString方法。
    • AgeException类
public class AgeException extends Exception{
        private String message;
        public AgeException(int age){
            message = "年龄设置为:" + age + "不合理!";
        }
        public String toString(){
            return message;
        }
}
  • Pet 类
public class Pet {
    private String name;
    private String sex;
    private String kind;
    private int age;
    {
        this.name = "未知";
    }
    public Pet(String kind){
        this.kind = kind ;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) throws AgeException{
        if(age >= 20 || age < 0){
          throw new AgeException(age);
        }else{
            this.age = age;
        }
    }
    public void eat(String food){
        System.out.println(name+"正在吃"+food);
    }
    public void sleep(){
        System.out.println(name+"正在睡觉");
    }
    public String bark(){
        return name+"在叫:";
    }
}
  • Master类
public class Master {
    public static void main(String[] args)  {
        Pet pet1 = new Dog("金毛");
        pet1.setName("旺财");
        try{
            pet1.setAge(30);
        }
        catch(AgeException e){
            e.printStackTrace();
        }
       pet1.eat("骨头");
        pet1.sleep();
        ((Dog)pet1).lookDoor();
        System.out.println(pet1.bark());
    }
}

  • 运行结果
    image.png
ljm要加油
原文地址:https://www.cnblogs.com/ljmmm1/p/14278358.html