• Java基础:异常怎么分类的(面试题:Exception和Error的区别),看完这篇就都捋清了


    1 Throwable类

    它是所有异常类型的根类。
    其下有2个直接子类:Exception 和 Error。

    注意:别看 Throwable 处于异常树形结构的最顶部,但它并不是一个接口,也不是一个抽象类,它是一个具体类。不信大家可以去看源码或JDK文档。
    它的类声明是这样的:

    public class Throwable extends Object implements Serializable { ... }
    

    2 Exception

    它是所有异常的根类。但是 Exception的子类中,可以分为两大类:检查型异常(即,编译时异常)和 非检查型异常(即,运行时异常)。

    2.1 检查型异常(checked exception)

    在编译时被检查并强制实施的异常。
    Java的检查型异常包含编译时检查,以确保实际抛出的是所说明的异常,并且异常说明是完整的(它要精确 地描述所有可能被抛出的异常)。相反,C++的异常说明只会在运⾏时检查。如果抛出的异常和异常说明不 符,C++程序将调⽤标准库函数 unexpected() 。

    2.2 ⾮检查型异常(unchecked exception)

    这个类别有⼀整组的异常类型。它们总是会被Java⾃动抛出,我们不需要将其包含在异常说明中。很⽅便的 是,它们都被放到了⼀个叫作 RuntimeException 的基类之下,这是继承的⼀个完美的⽰例:它建⽴了⼀个具 有某些共同特征和⾏为的类型家族。
    RuntimeException 代表的是编程错误,它包括以下错误。 1. ⽆法预料的错误,⽐如在我们控制之外的 null 引⽤。 2. 作为程序员,应该在代码中检查的错误(⽐如看到 ArrayIndexOutOfBoundsException ,我们就应该注意 数组的⼤⼩了)。在⼀个地⽅发⽣的异常,往往会变成另⼀个地⽅的问题。 这⾥异常对我们有巨⼤的好处,因为它们有助于调试。 我们从来不会在异常说明⾥说⼀个⽅法可能会抛出 RuntimeException (或者任何继承⾃ RuntimeException 的 类型),因为它们是“⾮检查型异常”(unchecked exception)。因为它们指出的是bug,会被⾃动处理,所 以我们通常不⽤捕捉 RuntimeException 。如果你必须检查 RuntimeException 的话,你的代码就会变得⾮常 乱。尽管我们通常不⽤捕捉 RuntimeException ,但是在⾃⼰的包中,我们有可能选择抛出某个 RuntimeException 。

    3 Error

    关于Error类,JDK文档中是这么说的:
    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
    A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

    文档中说Error,是 Throwable 的一个子类,它是表示那些不应该在程序中被捕获的严重问题。并且在方法声明的throws子句中,不需要显式声明任何Error或其子类。

    我说一个大家都见过的类 java.lang.OutOfMemoryError,一般程序出现内存溢出时就抛出这个错误类型,它的父类是 VirtualMachineError,而 VirtualMachineError的父类就是 Error。

    对了,还有一个大家更熟悉的例子:java.lang.StackOverflowError 。它也是VirtualMachineError的子类。JDK文件的对这种Error的说明很清晰:Thrown when a stack overflow occurs because an application recurses too deeply

  • 相关阅读:
    Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
    react 报错:'React' must be in scope when using JSX react/react-in-jsx-scope
    锋超R2200服务器U盘自检
    EF MySql 连接错误
    sqlalchemy插入数据遇到的一个BUG
    风哥Linux系统运维工程师培训实战教程(入门篇.共20套)
    Django
    Django
    Django 配置 sitemap 接口
    MySQL中 replace与replace into的区别与使用方法(干货分享)
  • 原文地址:https://www.cnblogs.com/mediocreWorld/p/16011053.html
Copyright © 2020-2023  润新知