Java异常类的继承关系图


注释:Error和RuntimeException属于Unchecked Exception(非检查异常);

try catch语句捕获多个异常时,如有诸如上述的继承关系,子类异常在前,父类的在后捕获 (1)Error:jvm中出现不可恢复的错误,如堆内存溢出等,程序是没有处理机会的。 (2)运行时异常(RuntimeException):属于非检查异常,java编译器忽略其抛出和检查,当在加载运行后,出现的异常;常见有:ArrayIndexOutofException、NumberFormatException、NullPointerException、ClassCastException、ClassNotFoundException等。 (3)非运行时异常:也叫可处理异常,程序编译时,就提示的异常。如:自定义异常、IOException、SQLException、FileNotFoundException等。 (4)自定义异常示例:自定义异常根据需求使用throw关键字引发异常。

//①自定义异常类继承Exception

class TestException extends Exception{
          
   

    String message = "";

    public TestException(String message) {

       this.message = message;

    }

    @Override

    public String toString() {

       return message;

    }

}

//②自定义异常用throw设置触发

public class Demo {
          
   

    public static void main(String[]args) throws Exception{

           String e = "asdfabc";

       if(e.contains("abc")){

           throw new TestException("包含非法字符");

       }

    }

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