java 异常机制

2021-04-14  本文已影响0人  马铃薯a

狂神视频笔记

java 异常机制

graph LR
Throwable-->Error-->VirtulMachineError-->StackOverFlowError
VirtulMachineError-->OutOfMemoryError
Error-->AWTError
Throwable-->Exception-->IOException-->EoFException
IOException-->FileNotFoundException
Exception-->RuntimeException
RuntimeException-->ArrithmeticException
RuntimeException-->MissingResourceException
RuntimeException-->ClassNotFoundException
RuntimeException-->NullPointerException
RuntimeException-->IllegalArgumentException
RuntimeException-->ArrayIndexOutOfBoundsException
RuntimeException-->UnkownTypeException

Error 异常

Exception 异常

try catch finally

try{
    /** 监控区域 */
}catch(想要捕获的异常类型){
    /** 捕获异常 */
}finally{
    /** 善后工作,无论是否捕获异常,都要执行 */
}

try{}catch(){
    
}catch(){
    
}catch(Throwable){
    // 从小到大捕获
}

throw 主动抛出异常

public void test(){
    int a = 0;
    if(a==0){
        /** 主动抛出异常, 一般在方法中使用 */
        throw new ArithmeticException();
    }
}

throws 在方法上抛出异常

public void test() throws ArithmeticException{
    
}

自定义异常

使用 java 内置的异常类可以描述在编程时出现的大部分异常情况. 初此之外, 用户还可以自定义异常. 用户自定义异常类, 只需要继承 Exception 类即可.

在程序中使用自定义异常类, 大体可分为以下几个步骤:

  1. 创建自定义异常类.
  2. 在方法中通过 throw 关键字抛出异常对象
  3. 如果在当前抛出异常的方法中处理异常, 可以使用 try-catch 语句捕获异常并处理;否则在方法的声明处通过 throws 关键字指明要抛出给方法调用者的异常, 继续执行下一步操作.
  4. 在出现异常方法的调用者中捕获并处理异常.

自定义的异常类

// 自定义的异常类
public class MyException extends Exception{
    // 传递数字 > 10;
    private int detail;
    
    public MyException(int a){
        this.detail = a;
    }
    
    @Override
    public String toString(){
        return "MyException{" + "detail" + detail + "}";
    }
}

实际应用中的经验总结

上一篇 下一篇

猜你喜欢

热点阅读