java 异常机制

狂神视频笔记

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 异常

  • Error类 对象 由 java 虚拟机生成并 抛出, 大多数错误与代码编写者所执行的操作无关.
  • java 虚拟机运行错误( Virtual MachineError), 当 JVM 不在有继续执行操作所需的内存资源时, 将出现 OutOfMemoryError. 这些异常发生时, java 虚拟机 (JVM) 一般会选择线程终止.
  • 还有发生在虚拟机视图执行应用时, 如类定义错误( NoClassDefFoundError), 链接错误( LinkageError ). 这些错误是不可查的, 因为它们在应用程序的控制和处理能力之外, 而且绝大数是程序运行时不允许出现的状况.

Exception 异常

  • 在 Exception 分支中有一个重要的子类 RuntimeException (运行时异常)
    • ArrayIndexOutBoundsException ( 数组下标越界 )
    • NullPointerException ( 空指针异常)
    • ArithmeticException (算数异常)
    • MissingResourceException (丢失资源)
    • ClassNotFoundException (找不到类) 等异常, 这些异常是不检查异常, 程序中可以选择捕获处理, 也可以不处理
  • 这些异常一般是由程序逻辑错误引起的, 程序应该从逻辑角度尽可能避免这类异常的发生.
  • Error 和 Exception 的区别: Error 通常是灾难性的致命错误, 是程序无法控制和处理的, 当出现这些异常时, java 虚拟机 ( Jvm ) 一般会选择终止线程; 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 + "}";
    }
}

实际应用中的经验总结

  • 处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch 处理
  • 在多重 catch 块后面, 可以加上一个 catch (Exception)来处理可能会被遗漏的异常
  • 对于不确定的代码, 也可以加上一个 try-catch, 处理潜在的异常
  • 尽量去处理异常, 切忌只是简单的调用 printStackTrace() 去打印输出
  • 具体如何处理异常, 要根据不同的业务需求和异常类型去决定
  • 尽量添加 finally 语句块去释放占用的资源

你可能感兴趣的:(java 异常机制)