Java异常

graph TD
A[Throwable]-->B[Error]
A-->C[Exception]
B-->D[VirtualMachineError]
D-->E[OutOfMemoryError]
C-->F[RuntimeException]
C-->G[IOEXception]
F-->H[ArithmeticException]
F-->I[NullPointerException]
F-->J[IndexOutOfBoundsException]
  • 除了RuntimeException,以外的都是比检异常,就是必须进行异常捕获的异常类型

异常的处理

  1. try--catch--finally

    • catch 语句块可以有多个
    • finally 不管是否发生异常都会执行,比如:Io异常时,finally常执行close()方法
  2. throws 关键字

    public void getFileMesg() throws IOException{
        
    }
    // 那么这个方法的调用者,就需要对这个异常进行捕获
    

主动抛出异常 和 自定义异常

  • 主动抛出异常 throw 关键字
try{
    
}catch(Exception e){
    throw e; // 直接抛出异常
}
  • 自定义异常 需要继承Exception(必检异常)或RuntimeException
class MyException extends Exception{
    
}

class MyException extends RuntimeException{
    
}

Throwable 的方法

Throwable(String message) //message为错误信息创建异常对象

String getMessage() // 获取错误信息 : 类名+错误信息,或类名

String toString() // 获取错误信息 : 类名+错误信息,或类名

void printStackTrace() //返回错误信息和栈信息;
原文地址:https://www.cnblogs.com/fiwen/p/9005380.html