JDK1.8源码学习--lang包(Throwable,Error,Exception)

前言


月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
 

一.Java中的异常

        异常是用一个Throwable类(Object的直接子类)或其子类的实例表示的.

        Throwable及其所有子类统统都是异常类.

        Exception和Erro类是Throwable的直接子类.

  • Exception是普通程序希望恢复的所有异常的超类
  • Error是普通程序通常不指望能够恢复的所有异常的超类

ps:以上摘抄自Java语言规范.

 

二.Throwable的作用

           直接看源码注释(我的翻译可能不太准,如果道友们有更棒的理解,可以留言或者私信)

/**
 * The {@code Throwable} class is the superclass of all errors and
 * exceptions in the Java language. Only objects that are instances of this
 * class (or one of its subclasses) are thrown by the Java Virtual Machine or
 * can be thrown by the Java {@code throw} statement. Similarly, only
 * this class or one of its subclasses can be the argument type in a
 * {@code catch} clause.
 * 1.Throwable类是 Java 语言中所有错误和异常的超类。只有属于此类(或其子类之一)的实例的对象
 * 才会被 Java 虚拟机抛出或可以被 Java throw语句抛出。
 * 类似地,只有此类或其子类之一可以是  catch子句中的参数类型
 * For the purposes of compile-time checking of exceptions, {@code
 * Throwable} and any subclass of {@code Throwable} that is not also a
 * subclass of either {@link RuntimeException} or {@link Error} are
 * regarded as checked exceptions.
 * 2.出于编译时异常检查的目的,Throwable和 Throwable的任何子类
 * (不是RuntimeException或  Error的子类)都被视为已检查异常
 * <p>Instances of two subclasses, {@link java.lang.Error} and
 * {@link java.lang.Exception}, are conventionally used to indicate
 * that exceptional situations have occurred. Typically, these instances
 * are freshly created in the context of the exceptional situation so
 * as to include relevant information (such as stack trace data).
 * 3.两个子类的实例,java.lang.Error和 java.lang.Exception,通常用于指示发生了异常情况。
 * 通常,这些实例是在异常情况的上下文中新创建的,以便包含相关信息(例如堆栈跟踪数据)
 * <p>A throwable contains a snapshot of the execution stack of its
 * thread at the time it was created. It can also contain a message
 * string that gives more information about the error. Over time, a
 * throwable can {@linkplain Throwable#addSuppressed suppress} other
 * throwables from being propagated.  Finally, the throwable can also
 * contain a <i>cause</i>: another throwable that caused this
 * throwable to be constructed.  The recording of this causal information
 * is referred to as the <i>chained exception</i> facility, as the
 * cause can, itself, have a cause, and so on, leading to a "chain" of
 * exceptions, each caused by another.
 * 4.throwable 包含创建时其线程的执行堆栈的快照,它还可以包含一个消息字符串,提供有关错误的更多信息
 * 5.随着时间的推移,一个throwable可以Throwable.addSuppressed抑制其他throwable被传播
 * 6.最后,throwable 还可以包含一个原因:另一个导致该 throwable 被构造的 throwable
 * 7.这种因果信息的记录被称为链式异常设施,因为原因本身可以有一个原因,等等,导致异常的“链”,每个异常都由另一个引起
 *
 * <p>One reason that a throwable may have a cause is that the class that
 * throws it is built atop a lower layered abstraction, and an operation on
 * the upper layer fails due to a failure in the lower layer.  It would be bad
 * design to let the throwable thrown by the lower layer propagate outward, as
 * it is generally unrelated to the abstraction provided by the upper layer.
 * Further, doing so would tie the API of the upper layer to the details of
 * its implementation, assuming the lower layer's exception was a checked
 * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
 * cause) allows the upper layer to communicate the details of the failure to
 * its caller without incurring either of these shortcomings.  It preserves
 * the flexibility to change the implementation of the upper layer without
 * changing its API (in particular, the set of exceptions thrown by its
 * methods).
 * 8.throwable可能有原因的一个原因是抛出它的类构建在较低层的抽象之上,并且由于较低层的失败而导致上层的操作失败
 * 9.让下层抛出的throwable向外传播是不好的设计,因为它通常与上层提供的抽象无关。
 * 10.此外,这样做会将上层的 API 与其实现的细节联系起来,假设下层的异常是已检查的异常
 * 11.抛出“包装异常”(即包含原因的异常)允许上层将失败的详细信息传达给其调用者,而不会导致这些缺点中的任何一个
 * 12.它保留了更改上层实现的灵活性,而无需更改其 API(特别是其方法抛出的异常集)
 * <p>A second reason that a throwable may have a cause is that the method
 * that throws it must conform to a general-purpose interface that does not
 * permit the method to throw the cause directly.  For example, suppose
 * a persistent collection conforms to the {@link java.util.Collection
 * Collection} interface, and that its persistence is implemented atop
 * {@code java.io}.  Suppose the internals of the {@code add} method
 * can throw an {@link java.io.IOException IOException}.  The implementation
 * can communicate the details of the {@code IOException} to its caller
 * while conforming to the {@code Collection} interface by wrapping the
 * {@code IOException} in an appropriate unchecked exception.  (The
 * specification for the persistent collection should indicate that it is
 * capable of throwing such exceptions.)
 *13.造成throwable的第二个原因可能是,抛出它的方法必须符合不允许该方法直接抛出原因的通用接口
 * 14.例如,假设一个持久化集合符合java.util.Collection接口,并且它的持久化是在java.io之上实现的。
 * 通过将 IOException包装在适当的未经检查的异常中,实现可以将 IOException的详细信息传达给其调用者,
 * 同时符合 Collection接口。 (持久集合的规范应该表明它能够抛出这样的异常。)
 * <p>A cause can be associated with a throwable in two ways: via a
 * constructor that takes the cause as an argument, or via the
 * {@link #initCause(Throwable)} method.  New throwable classes that
 * wish to allow causes to be associated with them should provide constructors
 * that take a cause and delegate (perhaps indirectly) to one of the
 * {@code Throwable} constructors that takes a cause.
 * 15.原因可以通过两种方式与 throwable 相关联:通过将原因作为参数的构造函数,或通过initCause(Throwable)方法
 * 16.希望允许原因与它们相关联的新可抛出类,应提供采用原因的构造函数并委托(可能间接地)给采用原因的 Throwable构造函数之一
 * Because the {@code initCause} method is public, it allows a cause to be
 * associated with any throwable, even a "legacy throwable" whose
 * implementation predates the addition of the exception chaining mechanism to
 * {@code Throwable}.
 * 17.因为 initCause方法是公开的,它允许将原因与任何可抛出的相关联,
 * 甚至是“遗留的可抛出”,其实现早于将异常链机制添加到 Throwable。
 * <p>By convention, class {@code Throwable} and its subclasses have two
 * constructors, one that takes no arguments and one that takes a
 * {@code String} argument that can be used to produce a detail message.
 * Further, those subclasses that might likely have a cause associated with
 * them should have two more constructors, one that takes a
 * {@code Throwable} (the cause), and one that takes a
 * {@code String} (the detail message) and a {@code Throwable} (the
 * cause).
 * 18.按照惯例,类Throwable及其子类有两个构造函数,一个不接受参数,另一个接受可用于生成详细消息的String参数
 * 19.此外,那些可能有相关原因的子类应该有两个以上的构造函数,其中一个采用 {@code Throwable}(原因),
 * 其二是一个采用 String(详细消息)和一个Throwable原因)
 * @author  unascribed
 * @author  Josh Bloch (Added exception chaining and programmatic access to
 *          stack trace in 1.4.)
 * @jls 11.2 Compile-Time Checking of Exceptions
 * @since JDK1.0
 */

三.Throwable成员变量: 

   /**
     * 本机代码在此槽中保存了一些堆栈回溯的指示
     */
    private transient Object backtrace;

    /**
     *关于 Throwable 的具体细节。例如,对于 FileNotFoundException,这包含无法找到的文件的名称。
     */
    private String detailMessage;

/**
     * 空堆栈的共享值
     */
    private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];

    /*
     * 1.为了让 Throwable 对象成为不可变的并且被 JVM 安全地重用,
     * 例如 OutOfMemoryErrors、响应用户操作的可写 Throwable 字段、
     * cause、stackTrace 和抑制异常遵循以下协议
     * 1).这些字段被初始化为一个非空的哨兵值,这表明该值在逻辑上没有被设置
     * 2) 向该字段写入空值表示禁止进一步写入
     * 3)哨兵值可以替换为另一个非空值
     * 2.例如,HotSpot JVM 的实现已经预先分配了 OutOfMemoryError 对象,以便更好地诊断这种情况。
     * 3.这些对象是在不调用该类的构造函数的情况下创建的,并且相关字段被初始化为 null
     * 4.为了支持此功能,添加到 Throwable 的任何新字段需要初始化为非空值,都需要协调 JVM 更改
     */

    /**
     * 导致该 throwable 被抛出的 throwable,如果该 throwable 不是由另一个 throwable 引起的,
     * 或者如果导致该 throwable 的原因未知,则为 null。如果这个字段等于这个throwable本身,
     * 说明这个throwable的原因还没有被初始化
     */
    private Throwable cause = this;

    /**
     * 1.getStackTrace()返回的堆栈跟踪
     * 2.该字段被初始化为零长度数组。此字段的 null值表示对setStackTrace(StackTraceElement[])
     */
    private StackTraceElement[] stackTrace = UNASSIGNED_STACK;


    //设置此静态字段会引入对一些 java.util 类的可接受的初始化依赖性
    private static final List<Throwable> SUPPRESSED_SENTINEL =
        Collections.unmodifiableList(new ArrayList<Throwable>(0));

    /**
     * 1.被抑制的异常列表,由getSuppressed()返回
     * 2.该列表被初始化为一个零元素不可修改的哨兵列表
     * 3.当读入序列化的 Throwable 时,如果 suppressExceptions字段指向零元素列表,则该字段将重置为哨兵值
     */
    private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;

    //尝试抑制空异常的消息
    private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";


    //试图压抑自己的消息
    private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";


    //用于标记导致异常堆栈跟踪的标题
    private static final String CAUSE_CAPTION = "Caused by: ";


    //用于标记被抑制的异常堆栈跟踪的标题
    private static final String SUPPRESSED_CAPTION = "Suppressed: ";

  //空的可抛数组
    private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];

四.Throwable内部类:

                SentinelHolder


    /**
     *  持有者类推迟初始化仅用于序列化的哨兵对象
     */
    private static class SentinelHolder {
        /**
         * 1.setStackTrace(StackTraceElement[]将堆栈跟踪设置为包含此标记值的单元素数组,
         * 表示将来设置堆栈跟踪的尝试将被忽略
         * 2.哨兵等于调用结果:new StackTraceElement("", "", null, Integer.MIN_VALUE)
         */
        public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
            new StackTraceElement("", "", null, Integer.MIN_VALUE);

        /**
         * 以串行形式使用的 Sentinel 值来指示不可变的堆栈跟踪
         */
        public static final StackTraceElement[] STACK_TRACE_SENTINEL =
            new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
    }

                PrintStreamOrWriter及其两个子类

/**
     * PrintStream 和 PrintWriter 的包装类以启用 printStackTrace 的单个实现
     */
    private abstract static class PrintStreamOrWriter {

        //返回使用此 StreamOrWriter 时要锁定的对象
        abstract Object lock();

        //在此 StreamOrWriter 上将指定的字符串打印为一行
        abstract void println(Object o);
    }


   private static class WrappedPrintStream extends PrintStreamOrWriter {
        private final PrintStream printStream;

        WrappedPrintStream(PrintStream printStream) {
            this.printStream = printStream;
        }

        Object lock() {
            return printStream;
        }

        void println(Object o) {
            printStream.println(o);
        }
    }

    private static class WrappedPrintWriter extends PrintStreamOrWriter {
        private final PrintWriter printWriter;

        WrappedPrintWriter(PrintWriter printWriter) {
            this.printWriter = printWriter;
        }

        Object lock() {
            return printWriter;
        }

        void println(Object o) {
            printWriter.println(o);
        }
    }

      五.Throwable构造方法:        

    /**
     * 1.使用 null作为详细消息构造一个新的 throwable。
     * 原因未初始化,随后可能会通过调用 initCause进行初始化
     * 2.调用 fillInStackTrace()方法对新创建的 throwable 中的堆栈跟踪数据进行初始化
     */
    public Throwable() {
        fillInStackTrace();
    }

    /**
     * 1.使用指定的详细消息构造一个新的 throwable。原因未初始化,随后可能会通过调用 initCause进行初始化。
     * 2.调用 fillInStackTrace()方法来初始化新创建的 throwable 中的堆栈跟踪数据
     */
    public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }

    /**
     * 1.使用指定的详细消息和原因构造一个新的 throwable。
     * 请注意,与 cause相关联的详细消息不会<自动合并到此 throwable 的详细消息中。
     * 2.调用 fillInStackTrace()方法来初始化新创建的 throwable 中的堆栈跟踪数据
     */
    public Throwable(String message, Throwable cause) {
        fillInStackTrace();
        detailMessage = message;
        this.cause = cause;
    }

    /**
     * 1.使用指定的原因和 (cause==null ? null :cause.toString())的详细消息
     * 构造一个新的 throwable(通常包含cause的类和详细消息)
     * 2.此构造函数对于仅是其他 throwable 的包装器的 throwable 很有用,
     * 例如,java.security.PrivilegedActionException
     * 3.调用 fillInStackTrace() 方法来初始化新创建的 throwable 中的堆栈跟踪数据
     */
    public Throwable(Throwable cause) {
        fillInStackTrace();
        detailMessage = (cause==null ? null : cause.toString());
        this.cause = cause;
    }

    /**
     * 1.使用指定的详细消息、原因、启用或禁用 addSuppressed 抑制以及启用或禁用可写堆栈跟踪构造一个新的 throwable。
     * 2.如果禁用了抑制,则此对象的 getSuppressed将返回一个零长度数组,并且调用 addSuppressed
     * 否则会将异常附加到抑制列表将无效
     * 3.如果可写堆栈跟踪为 false,则此构造函数不会调用fillInStackTrace(),
     * null将写入  stackTrace字段,随后调用fillInStackTrace 和 setStackTrace(StackTraceElement[])不会设置堆栈跟踪。
     * 4.请注意,Throwable的其他构造函数将抑制视为已启用,堆栈跟踪视为可写。
     * 5.Throwable的子类应该记录禁用抑制的任何条件以及记录堆栈跟踪不可写的条件。
     * 6.禁用抑制应该只发生在存在特殊要求的异常情况下,例如虚拟机在低内存情况下重用异常对象
     * 7.给定异常对象被重复捕获和重新抛出的情况,例如在两个子系统之间实现控制流,是另一种适合不可变抛出对象的情况。
     */
    protected Throwable(String message, Throwable cause,
                        boolean enableSuppression,
                        boolean writableStackTrace) {
        if (writableStackTrace) {
            fillInStackTrace();
        } else {
            stackTrace = null;
        }
        detailMessage = message;
        this.cause = cause;
        if (!enableSuppression)
            suppressedExceptions = null;
    }

   六.Throwable内部方法: 

                getMessage()

 /**
     * 返回此 throwable 的详细消息字符串
     */
    public String getMessage() {
        return detailMessage;
    }

/*
     * 1.创建此 throwable 的本地化描述,子类可以覆盖此方法以生成特定于语言环境的消息。
     * 2.对于不覆盖此方法的子类,默认实现返回与getMessage()相同的结果。
     */
    public String getLocalizedMessage() {
        return getMessage();
    }

                getCause

    /**
     * 1.如果原因不存在或未知,则返回此 throwable 的原因或null。 
     * (原因是导致这个 throwable 被抛出的 throwable。)
     * 2.此实现返回通过需要 Throwable的构造函数之一提供的原因,或者在使用 initCause(Throwable)方法创建后设置的原因
     * 3.虽然通常没有必要覆盖此方法,但子类可以覆盖它以返回通过其他方式设置的原因
     * 4.这适用于在将链式异常添加到 Throwable之前的“遗留链式可抛出”
     * 5.请注意,不需要覆盖任何PrintStackTrace方法,所有这些方法都会调用getCause方法来确定 throwable 的原因。
     */
    public synchronized Throwable getCause() {
        return (cause==this ? null : cause);
    }

                initCause

  /**

     * 1.将此 throwable 的 cause初始化为指定值。(原因是导致这个 throwable 被抛出的 throwable。)
     *2.该方法最多可以调用一次。它通常在构造函数中调用,或者在创建 throwable 之后立即调用。
     * 3.如果这个 throwable 是用Throwable(Throwable)或 Throwable(String,Throwable) 创建的,
     * 这个方法甚至不能被调用一次
     */
    public synchronized Throwable initCause(Throwable cause) {
        if (this.cause != this)
            throw new IllegalStateException("Can't overwrite cause with " +
                                            Objects.toString(cause, "a null"), this);
        if (cause == this)
            throw new IllegalArgumentException("Self-causation not permitted", this);
        this.cause = cause;
        return this;
    }

                toString()

   /**
     * 返回此 throwable 的简短描述。结果是:
     * 此对象的类的Class.getName() ": "(一个冒号和一个空格)
     * 调用此对象的  getLocalizedMessage方法的结果
     * 如果 getLocalizedMessage返回 null,则只返回类名。
     */
    public String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return (message != null) ? (s + ": " + message) : s;
    }

                printStackTrace()


    /**
     * 将此 throwable 及其回溯打印到指定的打印流
     */
    public void printStackTrace(PrintStream s) {
        printStackTrace(new WrappedPrintStream(s));
    }

 /**
     * 1.将此 throwable 及其回溯打印到标准错误流
     * 2.此方法在错误输出流上打印此 Throwable对象的堆栈跟踪,即字段System.err的值。
     * 3.输出的第一行包含此对象的 toString()方法的结果,剩余的行表示之前由方法fillInStackTrace()记录的数据。
     */
    public void printStackTrace() {
        printStackTrace(System.err);
    }

   /**
     * 1.填充执行堆栈跟踪。此方法在此 Throwable对象中记录有关当前线程的堆栈帧的当前状态的信息
     * 2.如果这个Throwable的堆栈跟踪Throwable(String, Throwable, boolean, boolean) 不可写,
     * 调用这个方法没有效果
     */
    public synchronized Throwable fillInStackTrace() {
        if (stackTrace != null ||
            backtrace != null /* Out of protocol state  超出协议状态*/ ) {
            fillInStackTrace(0);
            stackTrace = UNASSIGNED_STACK;
        }
        return this;
    }

                getStackTrace

   /**
     * 1.提供对 printStackTrace()打印的堆栈跟踪信息的编程访问
     * 2.返回一组堆栈跟踪元素,每个元素代表一个堆栈帧
     * 3.数组的第零个元素(假设数组的长度不为零)表示堆栈的顶部,这是序列中的最后一个方法调用
     * 4.通常,这是创建和抛出此 throwable 的点。数组的最后一个元素(假设数组的长度不为零)表示堆栈的底部,
     * 这是序列中的第一个方法调用。
     * 5.在某些情况下,某些虚拟机可能会从堆栈跟踪中省略一个或多个堆栈帧
     * 6.在极端情况下,允许没有与此 throwable 有关的堆栈跟踪信息的虚拟机从此方法返回零长度数组
     * 7.一般而言,此方法返回的数组将包含每个由 printStackTrace打印的帧的元素。写入返回的数组不会影响以后对此方法的调用
     */
    public StackTraceElement[] getStackTrace() {
        return getOurStackTrace().clone();
    }

                setStackTrace

   /**

     * 1.设置将由 getStackTrace()返回并由 printStackTrace()和相关方法打印的堆栈跟踪元素
     * 2.此方法是为 RPC 框架和其他高级系统设计的,允许客户端覆盖默认堆栈跟踪,
     * 该堆栈跟踪由 fillInStackTrace()在构造 throwable 时生成或在从 throwable 读取时反序列化序列化流
     * 3.<p>如果此 Throwable(String, Throwable, boolean, boolean) 的堆栈跟踪不可写,
     * 则调用此方法除了验证其参数外没有任何效果

     */
    public void setStackTrace(StackTraceElement[] stackTrace) {
        // Validate argument
        StackTraceElement[] defensiveCopy = stackTrace.clone();
        for (int i = 0; i < defensiveCopy.length; i++) {
            if (defensiveCopy[i] == null)
                throw new NullPointerException("stackTrace[" + i + "]");
        }

        synchronized (this) {
            if (this.stackTrace == null && // Immutable stack
                backtrace == null) // Test for out of protocol state
                return;
            this.stackTrace = defensiveCopy;
        }
    }

                addSuppressed/getSuppressed

    /**
     * 1.将指定的异常附加到为传递此异常而被抑制的异常。此方法是线程安全的,
     * 通常由 try-with-resources 语句调用(自动和隐式)
     * 2.通过构造函数启用抑制行为除非禁用 Throwable(String, Throwable, boolean, boolean)。
     * 当抑制被禁用时,这个方法除了验证它的参数之外什么都不做
     * 3.请注意,当一个异常initCause(Throwable) 导致另一个异常时,通常会捕获第一个异常,
     * 然后抛出第二个异常作为响应。换句话说,这两个例外之间存在因果关系
     * 4.相比之下,在兄弟代码块中可能会抛出两个独立的异常,
     * 特别是在  try-with-resources 语句的 try块和编译器生成的 finally关闭资源的块
     * 5.在这些情况下,只能传播抛出的异常之一。
     * 6.在 try-with-resources 语句中,当有两个这样的异常时,
     * 来自try块的异常被传播,来自 finally 块的异常被添加到被  try块中的异常抑制的异常。
     * 当异常展开堆栈时,它可以累积多个被抑制的异常
     * 7.一个异常可能抑制了异常,同时也由另一个异常引起。
     * 异常是否有原因在其创建时在语义上是已知的,这与异常是否会抑制其他异常不同,后者通常仅在抛出异常后确定。
     * 8.请注意,在存在多个同级异常并且只能传播一个异常的情况下,程序员编写的代码也可以利用调用此方法
     */
    public final synchronized void addSuppressed(Throwable exception) {
        if (exception == this)
            throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);

        if (exception == null)
            throw new NullPointerException(NULL_CAUSE_MESSAGE);

        if (suppressedExceptions == null) // Suppressed exceptions not recorded
            //未记录禁止的异常
            return;

        if (suppressedExceptions == SUPPRESSED_SENTINEL)
            suppressedExceptions = new ArrayList<>(1);

        suppressedExceptions.add(exception);
    }

   /**
     * 1.返回一个包含所有被抑制的异常的数组,通常是通过 try-with-resources 语句来传递这个异常。
     * 2.如果没有异常被抑制或 Throwable(String, Throwable, boolean, boolean) 抑制被禁用,则返回一个空数组。
     */
    public final synchronized Throwable[] getSuppressed() {
        if (suppressedExceptions == SUPPRESSED_SENTINEL ||
            suppressedExceptions == null)
            return EMPTY_THROWABLE_ARRAY;
        else
            return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
    }

七.Error的作用

                

/**
 * An {@code Error} is a subclass of {@code Throwable}
 * that indicates serious problems that a reasonable application
 * should not try to catch. Most such errors are abnormal conditions.
 * The {@code ThreadDeath} error, though a "normal" condition,
 * is also a subclass of {@code Error} because most applications
 * should not try to catch it.
 * 1.Error是Throwable的子类,表示合理的应用程序不应尝试捕获的严重问题
 * 2.大多数此类错误是异常情况。ThreadDeath错误虽然是“正常”条件,但也是Error的子类,因为大多数应用程序不应尝试捕获它
 * <p>
 * A method is not required to declare in its {@code throws}
 * clause any subclasses of {@code Error} that might be thrown
 * during the execution of the method but not caught, since these
 * errors are abnormal conditions that should never occur.
 * 3.方法不需要在其 throws子句中声明在方法执行期间可能抛出但未被捕获的Error的任何子类,因为这些错误是不应该发生的异常情况
 * That is, {@code Error} and its subclasses are regarded as unchecked
 * exceptions for the purposes of compile-time checking of exceptions.
 * 4.也就是说,出于编译时检查异常的目的,Error及其子类被视为未经检查的异常
 * @author  Frank Yellin
 * @see     java.lang.ThreadDeath
 * @jls 11.2 Compile-Time Checking of Exceptions
 * @since   JDK1.0
 */

八.Error的构造方法

   /**
     * 使用 null作为详细消息构造一个新错误。原因未初始化,随后可能会通过调用 initCause进行初始化
     */
    public Error() {
        super();
    }

    /**

     * 使用指定的详细消息构造一个新错误。原因未初始化,随后可能会通过调用 initCause进行初始化。
     */
    public Error(String message) {
        super(message);
    }

    /**
     * 使用指定的详细消息和原因构造一个新错误。请注意,与cause关联的详细消息不会自动合并到此错误的详细消息中。
     */
    public Error(String message, Throwable cause) {
        super(message, cause);
    }

    /*

     * 使用指定的原因和 (cause==null ? null :cause.toString())的详细消息构造一个新错误
     * (通常包含cause的类和详细消息)。此构造函数对于仅是其他 throwable 的包装器的错误很有用

     */
    public Error(Throwable cause) {
        super(cause);
    }

    /**

     * 使用指定的详细消息、原因、禁用启用或禁用以及启用或禁用可写堆栈跟踪构造新错误。
     */
    protected Error(String message, Throwable cause,
                    boolean enableSuppression,
                    boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

九.Exception的作用

/**
 * The class {@code Exception} and its subclasses are a form of
 * {@code Throwable} that indicates conditions that a reasonable
 * application might want to catch.
 * 1.Exception类及其子类是Throwable的一种形式,表示合理的应用程序可能想要捕获的条件。
 * <p>The class {@code Exception} and any subclasses that are not also
 * subclasses of {@link RuntimeException} are <em>checked
 * exceptions</em>.  Checked exceptions need to be declared in a
 * method or constructor's {@code throws} clause if they can be thrown
 * by the execution of the method or constructor and propagate outside
 * the method or constructor boundary.
 * 2.Exception类和任何不是  RuntimeException子类的子类都是检查异常
 * 3.如果检查异常可以通过方法或构造函数的执行抛出并传播到方法或构造函数边界之外,则需要在方法或构造函数的throws句中声明它们。
 * @author  Frank Yellin
 * @see     java.lang.Error
 * @jls 11.2 Compile-Time Checking of Exceptions
 * @since   JDK1.0
 */

十.Exception的构造函数

 /**
     * 使用  null作为其详细消息构造一个新异常。原因未初始化,随后可能会通过调用 initCause进行初始化
     */
    public Exception() {
        super();
    }

    /**
     * 构造具有指定详细消息的新异常。原因未初始化,随后可能会通过调用 initCause进行初始化
     */
    public Exception(String message) {
        super(message);
    }

    /**
     * 构造具有指定详细消息和原因的新异常。请注意,与 cause关联的详细消息不会自动合并到此异常的详细消息中。
     */
    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * 使用指定的原因和(cause==null ? null :cause.toString())的详细消息构造一个
     * 新异常(通常包含 cause 的类和详细消息)。此构造函数对于仅是其他 throwable 的包装器的异常很有用
     * (例如,java.security.PrivilegedActionException)
     */
    public Exception(Throwable cause) {
        super(cause);
    }

    /**
     * 构造一个具有指定详细消息、原因、禁用启用或禁用以及启用或禁用可写堆栈跟踪的新异常。
     */
    protected Exception(String message, Throwable cause,
                        boolean enableSuppression,
                        boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

十一.总结

        那么在座的各位,又写出来什么异常呢...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值