src/share/classes/java/lang/Throwable.java

Print this page




  35  * this class or one of its subclasses can be the argument type in a
  36  * {@code catch} clause.
  37  *
  38  * For the purposes of compile-time checking of exceptions, {@code
  39  * Throwable} and any subclass of {@code Throwable} that is not also a
  40  * subclass of either {@link RuntimeException} or {@link Error} are
  41  * regarded as checked exceptions.
  42  *
  43  * <p>Instances of two subclasses, {@link java.lang.Error} and
  44  * {@link java.lang.Exception}, are conventionally used to indicate
  45  * that exceptional situations have occurred. Typically, these instances
  46  * are freshly created in the context of the exceptional situation so
  47  * as to include relevant information (such as stack trace data).
  48  *
  49  * <p>A throwable contains a snapshot of the execution stack of its
  50  * thread at the time it was created. It can also contain a message
  51  * string that gives more information about the error. Over time, a
  52  * throwable can {@linkplain Throwable#addSuppressed suppress} other
  53  * throwables from being propagated.  Finally, the throwable can also
  54  * contain a <i>cause</i>: another throwable that caused this
  55  * throwable to get thrown.  The recording of this causal information
  56  * is referred to as the <i>chained exception</i> facility, as the
  57  * cause can, itself, have a cause, and so on, leading to a "chain" of
  58  * exceptions, each caused by another.
  59  *
  60  * <p>One reason that a throwable may have a cause is that the class that
  61  * throws it is built atop a lower layered abstraction, and an operation on
  62  * the upper layer fails due to a failure in the lower layer.  It would be bad
  63  * design to let the throwable thrown by the lower layer propagate outward, as
  64  * it is generally unrelated to the abstraction provided by the upper layer.
  65  * Further, doing so would tie the API of the upper layer to the details of
  66  * its implementation, assuming the lower layer's exception was a checked
  67  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
  68  * cause) allows the upper layer to communicate the details of the failure to
  69  * its caller without incurring either of these shortcomings.  It preserves
  70  * the flexibility to change the implementation of the upper layer without
  71  * changing its API (in particular, the set of exceptions thrown by its
  72  * methods).
  73  *
  74  * <p>A second reason that a throwable may have a cause is that the method
  75  * that throws it must conform to a general-purpose interface that does not


 266      * This constructor is useful for throwables that are little more than
 267      * wrappers for other throwables (for example, {@link
 268      * java.security.PrivilegedActionException}).
 269      *
 270      * <p>The {@link #fillInStackTrace()} method is called to initialize
 271      * the stack trace data in the newly created throwable.
 272      *
 273      * @param  cause the cause (which is saved for later retrieval by the
 274      *         {@link #getCause()} method).  (A {@code null} value is
 275      *         permitted, and indicates that the cause is nonexistent or
 276      *         unknown.)
 277      * @since  1.4
 278      */
 279     public Throwable(Throwable cause) {
 280         fillInStackTrace();
 281         detailMessage = (cause==null ? null : cause.toString());
 282         this.cause = cause;
 283     }
 284 
 285     /**



































 286      * Returns the detail message string of this throwable.
 287      *
 288      * @return  the detail message string of this {@code Throwable} instance
 289      *          (which may be {@code null}).
 290      */
 291     public String getMessage() {
 292         return detailMessage;
 293     }
 294 
 295     /**
 296      * Creates a localized description of this throwable.
 297      * Subclasses may override this method in order to produce a
 298      * locale-specific message.  For subclasses that do not override this
 299      * method, the default implementation returns the same result as
 300      * {@code getMessage()}.
 301      *
 302      * @return  The localized description of this throwable.
 303      * @since   JDK1.1
 304      */
 305     public String getLocalizedMessage() {


 813             stackTrace = EMPTY_STACK;
 814         }
 815 
 816     }
 817 
 818     /**
 819      * Write a {@code Throwable} object to a stream.
 820      */
 821     private synchronized void writeObject(ObjectOutputStream s)
 822         throws IOException {
 823         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 824         s.defaultWriteObject();
 825     }
 826 
 827     /**
 828      * Appends the specified exception to the exceptions that were
 829      * suppressed in order to deliver this exception. This method is
 830      * typically called (automatically and implicitly) by the {@code
 831      * try}-with-resources statement.
 832      *
 833      * If the first exception to be suppressed is {@code null}, that
 834      * indicates suppressed exception information will <em>not</em> be
 835      * recorded for this exception.  Subsequent calls to this method
 836      * will not record any suppressed exceptions.  Otherwise,
 837      * attempting to suppress {@code null} after an exception has
 838      * already been successfully suppressed results in a {@code
 839      * NullPointerException}.
 840      *
 841      * <p>Note that when one exception {@linkplain
 842      * #initCause(Throwable) causes} another exception, the first
 843      * exception is usually caught and then the second exception is
 844      * thrown in response.  In other words, there is a causal
 845      * connection between the two exceptions.
 846      *
 847      * In contrast, there are situations where two independent
 848      * exceptions can be thrown in sibling code blocks, in particular
 849      * in the {@code try} block of a {@code try}-with-resources
 850      * statement and the compiler-generated {@code finally} block
 851      * which closes the resource.
 852      *
 853      * In these situations, only one of the thrown exceptions can be
 854      * propagated.  In the {@code try}-with-resources statement, when
 855      * there are two such exceptions, the exception originating from
 856      * the {@code try} block is propagated and the exception from the
 857      * {@code finally} block is added to the list of exceptions
 858      * suppressed by the exception from the {@code try} block.  As an
 859      * exception unwinds the stack, it can accumulate multiple
 860      * suppressed exceptions.
 861      *
 862      * <p>An exception may have suppressed exceptions while also being
 863      * caused by another exception.  Whether or not an exception has a
 864      * cause is semantically known at the time of its creation, unlike
 865      * whether or not an exception will suppress other exceptions
 866      * which is typically only determined after an exception is
 867      * thrown.
 868      *
 869      * <p>Note that programmer written code is also able to take
 870      * advantage of calling this method in situations where there are
 871      * multiple sibling exceptions and only one can be propagated.
 872      *
 873      * @param exception the exception to be added to the list of
 874      *        suppressed exceptions
 875      * @throws IllegalArgumentException if {@code exception} is this
 876      *         throwable; a throwable cannot suppress itself.
 877      * @throws NullPointerException if {@code exception} is null and
 878      *         an exception has already been suppressed by this exception
 879      * @since 1.7
 880      */
 881     public final synchronized void addSuppressed(Throwable exception) {
 882         if (exception == this)
 883             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 884 
 885         if (exception == null) {
 886             if (suppressedExceptions == SUPPRESSED_SENTINEL) {
 887                 suppressedExceptions = null; // No suppression information recorded
 888                 return;
 889             } else
 890                 throw new NullPointerException(NULL_CAUSE_MESSAGE);
 891         } else {
 892             assert exception != null && exception != this;
 893 
 894             if (suppressedExceptions == null) // Suppressed exceptions not recorded
 895                 return;
 896 
 897             if (suppressedExceptions == SUPPRESSED_SENTINEL)
 898                 suppressedExceptions = new ArrayList<>(1);
 899 
 900             assert suppressedExceptions != SUPPRESSED_SENTINEL;
 901 
 902             suppressedExceptions.add(exception);
 903         }
 904     }
 905 
 906     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 907 
 908     /**
 909      * Returns an array containing all of the exceptions that were
 910      * suppressed, typically by the {@code try}-with-resources
 911      * statement, in order to deliver this exception.
 912      *
 913      * If no exceptions were suppressed, an empty array is returned.


 914      *
 915      * @return an array containing all of the exceptions that were
 916      *         suppressed to deliver this exception.
 917      * @since 1.7
 918      */
 919     public final synchronized Throwable[] getSuppressed() {
 920         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
 921             suppressedExceptions == null)
 922             return EMPTY_THROWABLE_ARRAY;
 923         else
 924             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 925     }
 926 }


  35  * this class or one of its subclasses can be the argument type in a
  36  * {@code catch} clause.
  37  *
  38  * For the purposes of compile-time checking of exceptions, {@code
  39  * Throwable} and any subclass of {@code Throwable} that is not also a
  40  * subclass of either {@link RuntimeException} or {@link Error} are
  41  * regarded as checked exceptions.
  42  *
  43  * <p>Instances of two subclasses, {@link java.lang.Error} and
  44  * {@link java.lang.Exception}, are conventionally used to indicate
  45  * that exceptional situations have occurred. Typically, these instances
  46  * are freshly created in the context of the exceptional situation so
  47  * as to include relevant information (such as stack trace data).
  48  *
  49  * <p>A throwable contains a snapshot of the execution stack of its
  50  * thread at the time it was created. It can also contain a message
  51  * string that gives more information about the error. Over time, a
  52  * throwable can {@linkplain Throwable#addSuppressed suppress} other
  53  * throwables from being propagated.  Finally, the throwable can also
  54  * contain a <i>cause</i>: another throwable that caused this
  55  * throwable to be constructed.  The recording of this causal information
  56  * is referred to as the <i>chained exception</i> facility, as the
  57  * cause can, itself, have a cause, and so on, leading to a "chain" of
  58  * exceptions, each caused by another.
  59  *
  60  * <p>One reason that a throwable may have a cause is that the class that
  61  * throws it is built atop a lower layered abstraction, and an operation on
  62  * the upper layer fails due to a failure in the lower layer.  It would be bad
  63  * design to let the throwable thrown by the lower layer propagate outward, as
  64  * it is generally unrelated to the abstraction provided by the upper layer.
  65  * Further, doing so would tie the API of the upper layer to the details of
  66  * its implementation, assuming the lower layer's exception was a checked
  67  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
  68  * cause) allows the upper layer to communicate the details of the failure to
  69  * its caller without incurring either of these shortcomings.  It preserves
  70  * the flexibility to change the implementation of the upper layer without
  71  * changing its API (in particular, the set of exceptions thrown by its
  72  * methods).
  73  *
  74  * <p>A second reason that a throwable may have a cause is that the method
  75  * that throws it must conform to a general-purpose interface that does not


 266      * This constructor is useful for throwables that are little more than
 267      * wrappers for other throwables (for example, {@link
 268      * java.security.PrivilegedActionException}).
 269      *
 270      * <p>The {@link #fillInStackTrace()} method is called to initialize
 271      * the stack trace data in the newly created throwable.
 272      *
 273      * @param  cause the cause (which is saved for later retrieval by the
 274      *         {@link #getCause()} method).  (A {@code null} value is
 275      *         permitted, and indicates that the cause is nonexistent or
 276      *         unknown.)
 277      * @since  1.4
 278      */
 279     public Throwable(Throwable cause) {
 280         fillInStackTrace();
 281         detailMessage = (cause==null ? null : cause.toString());
 282         this.cause = cause;
 283     }
 284 
 285     /**
 286      * Constructs a new throwable with the specified detail message,
 287      * cause, and {@linkplain #addSuppressed suppression} enabled or
 288      * disabled.  If suppression is disabled, {@link #getSuppressed}
 289      * for this object will return a zero-length array and calls to
 290      * {@link #addSuppressed} that would otherwise append an exception
 291      * to the suppressed list will have no effect.
 292      *
 293      * <p>Note that the other constructors of {@code Throwable} treat
 294      * suppression as being enabled.  Subclasses of {@code Throwable}
 295      * should document any conditions under which suppression is
 296      * disabled.  Disabling of suppression should only occur in
 297      * exceptional circumstances where special requirements exist,
 298      * such as a virtual machine reusing exception objects under
 299      * low-memory situations.
 300      *
 301      * @param  message the detail message.
 302      * @param cause the cause.  (A {@code null} value is permitted,
 303      * and indicates that the cause is nonexistent or unknown.)
 304      * @param enableSuppression whether or not suppression is enabled or disabled
 305      *
 306      * @see OutOfMemoryError
 307      * @see NullPointerException
 308      * @see ArithmeticException
 309      * @since 1.7
 310      */
 311     protected Throwable(String message, Throwable cause,
 312                         boolean enableSuppression) {
 313         fillInStackTrace();
 314         detailMessage = message;
 315         this.cause = cause;
 316         if (!enableSuppression)
 317             suppressedExceptions = null;
 318     }
 319 
 320     /**
 321      * Returns the detail message string of this throwable.
 322      *
 323      * @return  the detail message string of this {@code Throwable} instance
 324      *          (which may be {@code null}).
 325      */
 326     public String getMessage() {
 327         return detailMessage;
 328     }
 329 
 330     /**
 331      * Creates a localized description of this throwable.
 332      * Subclasses may override this method in order to produce a
 333      * locale-specific message.  For subclasses that do not override this
 334      * method, the default implementation returns the same result as
 335      * {@code getMessage()}.
 336      *
 337      * @return  The localized description of this throwable.
 338      * @since   JDK1.1
 339      */
 340     public String getLocalizedMessage() {


 848             stackTrace = EMPTY_STACK;
 849         }
 850 
 851     }
 852 
 853     /**
 854      * Write a {@code Throwable} object to a stream.
 855      */
 856     private synchronized void writeObject(ObjectOutputStream s)
 857         throws IOException {
 858         getOurStackTrace();  // Ensure that stackTrace field is initialized.
 859         s.defaultWriteObject();
 860     }
 861 
 862     /**
 863      * Appends the specified exception to the exceptions that were
 864      * suppressed in order to deliver this exception. This method is
 865      * typically called (automatically and implicitly) by the {@code
 866      * try}-with-resources statement.
 867      *
 868      * <p>The suppression behavior is enabled <em>unless</em> disabled
 869      * {@linkplain #Throwable(String, Throwable, boolean) via a
 870      * constructor}.  When suppression is disabled, this method does
 871      * nothing other than to validate its argument.



 872      *
 873      * <p>Note that when one exception {@linkplain
 874      * #initCause(Throwable) causes} another exception, the first
 875      * exception is usually caught and then the second exception is
 876      * thrown in response.  In other words, there is a causal
 877      * connection between the two exceptions.
 878      *
 879      * In contrast, there are situations where two independent
 880      * exceptions can be thrown in sibling code blocks, in particular
 881      * in the {@code try} block of a {@code try}-with-resources
 882      * statement and the compiler-generated {@code finally} block
 883      * which closes the resource.
 884      *
 885      * In these situations, only one of the thrown exceptions can be
 886      * propagated.  In the {@code try}-with-resources statement, when
 887      * there are two such exceptions, the exception originating from
 888      * the {@code try} block is propagated and the exception from the
 889      * {@code finally} block is added to the list of exceptions
 890      * suppressed by the exception from the {@code try} block.  As an
 891      * exception unwinds the stack, it can accumulate multiple
 892      * suppressed exceptions.
 893      *
 894      * <p>An exception may have suppressed exceptions while also being
 895      * caused by another exception.  Whether or not an exception has a
 896      * cause is semantically known at the time of its creation, unlike
 897      * whether or not an exception will suppress other exceptions
 898      * which is typically only determined after an exception is
 899      * thrown.
 900      *
 901      * <p>Note that programmer written code is also able to take
 902      * advantage of calling this method in situations where there are
 903      * multiple sibling exceptions and only one can be propagated.
 904      *
 905      * @param exception the exception to be added to the list of
 906      *        suppressed exceptions
 907      * @throws IllegalArgumentException if {@code exception} is this
 908      *         throwable; a throwable cannot suppress itself.
 909      * @throws NullPointerException if {@code exception} is {@code null}

 910      * @since 1.7
 911      */
 912     public final synchronized void addSuppressed(Throwable exception) {
 913         if (exception == this)
 914             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 915 
 916         if (exception == null)




 917             throw new NullPointerException(NULL_CAUSE_MESSAGE);


 918 
 919         if (suppressedExceptions == null) // Suppressed exceptions not recorded
 920             return;
 921 
 922         if (suppressedExceptions == SUPPRESSED_SENTINEL)
 923             suppressedExceptions = new ArrayList<>(1);
 924 


 925         suppressedExceptions.add(exception);
 926     }

 927 
 928     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 929 
 930     /**
 931      * Returns an array containing all of the exceptions that were
 932      * suppressed, typically by the {@code try}-with-resources
 933      * statement, in order to deliver this exception.
 934      *
 935      * If no exceptions were suppressed or {@linkplain
 936      * Throwable(String, Throwable, boolean) suppression is disabled},
 937      * an empty array is returned.
 938      *
 939      * @return an array containing all of the exceptions that were
 940      *         suppressed to deliver this exception.
 941      * @since 1.7
 942      */
 943     public final synchronized Throwable[] getSuppressed() {
 944         if (suppressedExceptions == SUPPRESSED_SENTINEL ||
 945             suppressedExceptions == null)
 946             return EMPTY_THROWABLE_ARRAY;
 947         else
 948             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 949     }
 950 }