Throwable.java revision 2607
0N/A/*
2362N/A * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.lang;
0N/Aimport java.io.*;
2548N/Aimport java.util.*;
0N/A
0N/A/**
2607N/A * The {@code Throwable} class is the superclass of all errors and
0N/A * exceptions in the Java language. Only objects that are instances of this
0N/A * class (or one of its subclasses) are thrown by the Java Virtual Machine or
2607N/A * can be thrown by the Java {@code throw} statement. Similarly, only
0N/A * this class or one of its subclasses can be the argument type in a
2607N/A * {@code catch} clause.
0N/A *
2081N/A * For the purposes of compile-time checking of exceptions, {@code
2081N/A * Throwable} and any subclass of {@code Throwable} that is not also a
2081N/A * subclass of either {@link RuntimeException} or {@link Error} are
2081N/A * regarded as checked exceptions.
2081N/A *
0N/A * <p>Instances of two subclasses, {@link java.lang.Error} and
0N/A * {@link java.lang.Exception}, are conventionally used to indicate
0N/A * that exceptional situations have occurred. Typically, these instances
0N/A * are freshly created in the context of the exceptional situation so
0N/A * as to include relevant information (such as stack trace data).
0N/A *
0N/A * <p>A throwable contains a snapshot of the execution stack of its thread at
0N/A * the time it was created. It can also contain a message string that gives
0N/A * more information about the error. Finally, it can contain a <i>cause</i>:
0N/A * another throwable that caused this throwable to get thrown. The cause
0N/A * facility is new in release 1.4. It is also known as the <i>chained
0N/A * exception</i> facility, as the cause can, itself, have a cause, and so on,
0N/A * leading to a "chain" of exceptions, each caused by another.
0N/A *
0N/A * <p>One reason that a throwable may have a cause is that the class that
0N/A * throws it is built atop a lower layered abstraction, and an operation on
0N/A * the upper layer fails due to a failure in the lower layer. It would be bad
0N/A * design to let the throwable thrown by the lower layer propagate outward, as
0N/A * it is generally unrelated to the abstraction provided by the upper layer.
0N/A * Further, doing so would tie the API of the upper layer to the details of
0N/A * its implementation, assuming the lower layer's exception was a checked
0N/A * exception. Throwing a "wrapped exception" (i.e., an exception containing a
0N/A * cause) allows the upper layer to communicate the details of the failure to
0N/A * its caller without incurring either of these shortcomings. It preserves
0N/A * the flexibility to change the implementation of the upper layer without
0N/A * changing its API (in particular, the set of exceptions thrown by its
0N/A * methods).
0N/A *
0N/A * <p>A second reason that a throwable may have a cause is that the method
0N/A * that throws it must conform to a general-purpose interface that does not
0N/A * permit the method to throw the cause directly. For example, suppose
0N/A * a persistent collection conforms to the {@link java.util.Collection
0N/A * Collection} interface, and that its persistence is implemented atop
2607N/A * {@code java.io}. Suppose the internals of the {@code add} method
0N/A * can throw an {@link java.io.IOException IOException}. The implementation
2607N/A * can communicate the details of the {@code IOException} to its caller
2607N/A * while conforming to the {@code Collection} interface by wrapping the
2607N/A * {@code IOException} in an appropriate unchecked exception. (The
0N/A * specification for the persistent collection should indicate that it is
0N/A * capable of throwing such exceptions.)
0N/A *
0N/A * <p>A cause can be associated with a throwable in two ways: via a
0N/A * constructor that takes the cause as an argument, or via the
0N/A * {@link #initCause(Throwable)} method. New throwable classes that
0N/A * wish to allow causes to be associated with them should provide constructors
0N/A * that take a cause and delegate (perhaps indirectly) to one of the
2607N/A * {@code Throwable} constructors that takes a cause. For example:
0N/A * <pre>
0N/A * try {
0N/A * lowLevelOp();
0N/A * } catch (LowLevelException le) {
0N/A * throw new HighLevelException(le); // Chaining-aware constructor
0N/A * }
0N/A * </pre>
2607N/A * Because the {@code initCause} method is public, it allows a cause to be
0N/A * associated with any throwable, even a "legacy throwable" whose
0N/A * implementation predates the addition of the exception chaining mechanism to
2607N/A * {@code Throwable}. For example:
0N/A * <pre>
0N/A * try {
0N/A * lowLevelOp();
0N/A * } catch (LowLevelException le) {
0N/A * throw (HighLevelException)
2548N/A * new HighLevelException().initCause(le); // Legacy constructor
0N/A * }
0N/A * </pre>
0N/A *
0N/A * <p>Prior to release 1.4, there were many throwables that had their own
0N/A * non-standard exception chaining mechanisms (
0N/A * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
0N/A * {@link java.lang.reflect.UndeclaredThrowableException},
0N/A * {@link java.lang.reflect.InvocationTargetException},
0N/A * {@link java.io.WriteAbortedException},
0N/A * {@link java.security.PrivilegedActionException},
0N/A * {@link java.awt.print.PrinterIOException},
0N/A * {@link java.rmi.RemoteException} and
0N/A * {@link javax.naming.NamingException}).
0N/A * All of these throwables have been retrofitted to
0N/A * use the standard exception chaining mechanism, while continuing to
0N/A * implement their "legacy" chaining mechanisms for compatibility.
0N/A *
2607N/A * <p>Further, as of release 1.4, many general purpose {@code Throwable}
0N/A * classes (for example {@link Exception}, {@link RuntimeException},
0N/A * {@link Error}) have been retrofitted with constructors that take
0N/A * a cause. This was not strictly necessary, due to the existence of the
2607N/A * {@code initCause} method, but it is more convenient and expressive to
0N/A * delegate to a constructor that takes a cause.
0N/A *
2607N/A * <p>By convention, class {@code Throwable} and its subclasses have two
0N/A * constructors, one that takes no arguments and one that takes a
2607N/A * {@code String} argument that can be used to produce a detail message.
0N/A * Further, those subclasses that might likely have a cause associated with
0N/A * them should have two more constructors, one that takes a
2607N/A * {@code Throwable} (the cause), and one that takes a
2607N/A * {@code String} (the detail message) and a {@code Throwable} (the
0N/A * cause).
0N/A *
0N/A * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
0N/A * which allows programmatic access to the stack trace information that was
0N/A * previously available only in text form, via the various forms of the
0N/A * {@link #printStackTrace()} method. This information has been added to the
2607N/A * <i>serialized representation</i> of this class so {@code getStackTrace}
2607N/A * and {@code printStackTrace} will operate properly on a throwable that
0N/A * was obtained by deserialization.
0N/A *
0N/A * @author unascribed
0N/A * @author Josh Bloch (Added exception chaining and programmatic access to
0N/A * stack trace in 1.4.)
2081N/A * @jls3 11.2 Compile-Time Checking of Exceptions
0N/A * @since JDK1.0
0N/A */
0N/Apublic class Throwable implements Serializable {
0N/A /** use serialVersionUID from JDK 1.0.2 for interoperability */
0N/A private static final long serialVersionUID = -3042686055658047285L;
0N/A
0N/A /**
0N/A * Native code saves some indication of the stack backtrace in this slot.
0N/A */
0N/A private transient Object backtrace;
0N/A
0N/A /**
0N/A * Specific details about the Throwable. For example, for
2607N/A * {@code FileNotFoundException}, this contains the name of
0N/A * the file that could not be found.
0N/A *
0N/A * @serial
0N/A */
0N/A private String detailMessage;
0N/A
0N/A /**
0N/A * The throwable that caused this throwable to get thrown, or null if this
0N/A * throwable was not caused by another throwable, or if the causative
0N/A * throwable is unknown. If this field is equal to this throwable itself,
0N/A * it indicates that the cause of this throwable has not yet been
0N/A * initialized.
0N/A *
0N/A * @serial
0N/A * @since 1.4
0N/A */
0N/A private Throwable cause = this;
0N/A
0N/A /**
0N/A * The stack trace, as returned by {@link #getStackTrace()}.
0N/A *
0N/A * @serial
0N/A * @since 1.4
0N/A */
0N/A private StackTraceElement[] stackTrace;
0N/A /*
0N/A * This field is lazily initialized on first use or serialization and
0N/A * nulled out when fillInStackTrace is called.
0N/A */
0N/A
0N/A /**
2548N/A * The list of suppressed exceptions, as returned by
2548N/A * {@link #getSuppressedExceptions()}.
2548N/A *
2548N/A * @serial
2548N/A * @since 1.7
2548N/A */
2548N/A private List<Throwable> suppressedExceptions = Collections.emptyList();
2548N/A
2548N/A /** Message for trying to suppress a null exception. */
2548N/A private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
2548N/A
2548N/A /** Caption for labeling causative exception stack traces */
2548N/A private static final String CAUSE_CAPTION = "Caused by: ";
2548N/A
2548N/A /** Caption for labeling suppressed exception stack traces */
2548N/A private static final String SUPPRESSED_CAPTION = "Suppressed: ";
2548N/A
2548N/A /**
2607N/A * Constructs a new throwable with {@code null} as its detail message.
0N/A * The cause is not initialized, and may subsequently be initialized by a
0N/A * call to {@link #initCause}.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A */
0N/A public Throwable() {
0N/A fillInStackTrace();
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified detail message. The
0N/A * cause is not initialized, and may subsequently be initialized by
0N/A * a call to {@link #initCause}.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param message the detail message. The detail message is saved for
0N/A * later retrieval by the {@link #getMessage()} method.
0N/A */
0N/A public Throwable(String message) {
0N/A fillInStackTrace();
0N/A detailMessage = message;
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified detail message and
0N/A * cause. <p>Note that the detail message associated with
2607N/A * {@code cause} is <i>not</i> automatically incorporated in
0N/A * this throwable's detail message.
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param message the detail message (which is saved for later retrieval
0N/A * by the {@link #getMessage()} method).
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
0N/A * @since 1.4
0N/A */
0N/A public Throwable(String message, Throwable cause) {
0N/A fillInStackTrace();
0N/A detailMessage = message;
0N/A this.cause = cause;
0N/A }
0N/A
0N/A /**
0N/A * Constructs a new throwable with the specified cause and a detail
2607N/A * message of {@code (cause==null ? null : cause.toString())} (which
2607N/A * typically contains the class and detail message of {@code cause}).
0N/A * This constructor is useful for throwables that are little more than
0N/A * wrappers for other throwables (for example, {@link
0N/A * java.security.PrivilegedActionException}).
0N/A *
0N/A * <p>The {@link #fillInStackTrace()} method is called to initialize
0N/A * the stack trace data in the newly created throwable.
0N/A *
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
0N/A * @since 1.4
0N/A */
0N/A public Throwable(Throwable cause) {
0N/A fillInStackTrace();
0N/A detailMessage = (cause==null ? null : cause.toString());
0N/A this.cause = cause;
0N/A }
0N/A
0N/A /**
0N/A * Returns the detail message string of this throwable.
0N/A *
2607N/A * @return the detail message string of this {@code Throwable} instance
2607N/A * (which may be {@code null}).
0N/A */
0N/A public String getMessage() {
0N/A return detailMessage;
0N/A }
0N/A
0N/A /**
0N/A * Creates a localized description of this throwable.
0N/A * Subclasses may override this method in order to produce a
0N/A * locale-specific message. For subclasses that do not override this
0N/A * method, the default implementation returns the same result as
2607N/A * {@code getMessage()}.
0N/A *
0N/A * @return The localized description of this throwable.
0N/A * @since JDK1.1
0N/A */
0N/A public String getLocalizedMessage() {
0N/A return getMessage();
0N/A }
0N/A
0N/A /**
2607N/A * Returns the cause of this throwable or {@code null} if the
0N/A * cause is nonexistent or unknown. (The cause is the throwable that
0N/A * caused this throwable to get thrown.)
0N/A *
0N/A * <p>This implementation returns the cause that was supplied via one of
2607N/A * the constructors requiring a {@code Throwable}, or that was set after
0N/A * creation with the {@link #initCause(Throwable)} method. While it is
0N/A * typically unnecessary to override this method, a subclass can override
0N/A * it to return a cause set by some other means. This is appropriate for
0N/A * a "legacy chained throwable" that predates the addition of chained
2607N/A * exceptions to {@code Throwable}. Note that it is <i>not</i>
2607N/A * necessary to override any of the {@code PrintStackTrace} methods,
2607N/A * all of which invoke the {@code getCause} method to determine the
0N/A * cause of a throwable.
0N/A *
2607N/A * @return the cause of this throwable or {@code null} if the
0N/A * cause is nonexistent or unknown.
0N/A * @since 1.4
0N/A */
0N/A public Throwable getCause() {
0N/A return (cause==this ? null : cause);
0N/A }
0N/A
0N/A /**
0N/A * Initializes the <i>cause</i> of this throwable to the specified value.
0N/A * (The cause is the throwable that caused this throwable to get thrown.)
0N/A *
0N/A * <p>This method can be called at most once. It is generally called from
0N/A * within the constructor, or immediately after creating the
0N/A * throwable. If this throwable was created
0N/A * with {@link #Throwable(Throwable)} or
0N/A * {@link #Throwable(String,Throwable)}, this method cannot be called
0N/A * even once.
0N/A *
0N/A * @param cause the cause (which is saved for later retrieval by the
2607N/A * {@link #getCause()} method). (A {@code null} value is
0N/A * permitted, and indicates that the cause is nonexistent or
0N/A * unknown.)
2607N/A * @return a reference to this {@code Throwable} instance.
2607N/A * @throws IllegalArgumentException if {@code cause} is this
0N/A * throwable. (A throwable cannot be its own cause.)
0N/A * @throws IllegalStateException if this throwable was
0N/A * created with {@link #Throwable(Throwable)} or
0N/A * {@link #Throwable(String,Throwable)}, or this method has already
0N/A * been called on this throwable.
0N/A * @since 1.4
0N/A */
0N/A public synchronized Throwable initCause(Throwable cause) {
0N/A if (this.cause != this)
0N/A throw new IllegalStateException("Can't overwrite cause");
0N/A if (cause == this)
0N/A throw new IllegalArgumentException("Self-causation not permitted");
0N/A this.cause = cause;
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Returns a short description of this throwable.
0N/A * The result is the concatenation of:
0N/A * <ul>
0N/A * <li> the {@linkplain Class#getName() name} of the class of this object
0N/A * <li> ": " (a colon and a space)
0N/A * <li> the result of invoking this object's {@link #getLocalizedMessage}
0N/A * method
0N/A * </ul>
2607N/A * If {@code getLocalizedMessage} returns {@code null}, then just
0N/A * the class name is returned.
0N/A *
0N/A * @return a string representation of this throwable.
0N/A */
0N/A public String toString() {
0N/A String s = getClass().getName();
0N/A String message = getLocalizedMessage();
0N/A return (message != null) ? (s + ": " + message) : s;
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the
0N/A * standard error stream. This method prints a stack trace for this
2607N/A * {@code Throwable} object on the error output stream that is
2607N/A * the value of the field {@code System.err}. The first line of
0N/A * output contains the result of the {@link #toString()} method for
0N/A * this object. Remaining lines represent data previously recorded by
0N/A * the method {@link #fillInStackTrace()}. The format of this
0N/A * information depends on the implementation, but the following
0N/A * example may be regarded as typical:
0N/A * <blockquote><pre>
0N/A * java.lang.NullPointerException
0N/A * at MyClass.mash(MyClass.java:9)
0N/A * at MyClass.crunch(MyClass.java:6)
0N/A * at MyClass.main(MyClass.java:3)
0N/A * </pre></blockquote>
0N/A * This example was produced by running the program:
0N/A * <pre>
0N/A * class MyClass {
0N/A * public static void main(String[] args) {
0N/A * crunch(null);
0N/A * }
0N/A * static void crunch(int[] a) {
0N/A * mash(a);
0N/A * }
0N/A * static void mash(int[] b) {
0N/A * System.out.println(b[0]);
0N/A * }
0N/A * }
0N/A * </pre>
0N/A * The backtrace for a throwable with an initialized, non-null cause
0N/A * should generally include the backtrace for the cause. The format
0N/A * of this information depends on the implementation, but the following
0N/A * example may be regarded as typical:
0N/A * <pre>
0N/A * HighLevelException: MidLevelException: LowLevelException
0N/A * at Junk.a(Junk.java:13)
0N/A * at Junk.main(Junk.java:4)
0N/A * Caused by: MidLevelException: LowLevelException
0N/A * at Junk.c(Junk.java:23)
0N/A * at Junk.b(Junk.java:17)
0N/A * at Junk.a(Junk.java:11)
0N/A * ... 1 more
0N/A * Caused by: LowLevelException
0N/A * at Junk.e(Junk.java:30)
0N/A * at Junk.d(Junk.java:27)
0N/A * at Junk.c(Junk.java:21)
0N/A * ... 3 more
0N/A * </pre>
2607N/A * Note the presence of lines containing the characters {@code "..."}.
0N/A * These lines indicate that the remainder of the stack trace for this
0N/A * exception matches the indicated number of frames from the bottom of the
0N/A * stack trace of the exception that was caused by this exception (the
0N/A * "enclosing" exception). This shorthand can greatly reduce the length
0N/A * of the output in the common case where a wrapped exception is thrown
0N/A * from same method as the "causative exception" is caught. The above
0N/A * example was produced by running the program:
0N/A * <pre>
0N/A * public class Junk {
0N/A * public static void main(String args[]) {
0N/A * try {
0N/A * a();
0N/A * } catch(HighLevelException e) {
0N/A * e.printStackTrace();
0N/A * }
0N/A * }
0N/A * static void a() throws HighLevelException {
0N/A * try {
0N/A * b();
0N/A * } catch(MidLevelException e) {
0N/A * throw new HighLevelException(e);
0N/A * }
0N/A * }
0N/A * static void b() throws MidLevelException {
0N/A * c();
0N/A * }
0N/A * static void c() throws MidLevelException {
0N/A * try {
0N/A * d();
0N/A * } catch(LowLevelException e) {
0N/A * throw new MidLevelException(e);
0N/A * }
0N/A * }
0N/A * static void d() throws LowLevelException {
0N/A * e();
0N/A * }
0N/A * static void e() throws LowLevelException {
0N/A * throw new LowLevelException();
0N/A * }
0N/A * }
0N/A *
0N/A * class HighLevelException extends Exception {
0N/A * HighLevelException(Throwable cause) { super(cause); }
0N/A * }
0N/A *
0N/A * class MidLevelException extends Exception {
0N/A * MidLevelException(Throwable cause) { super(cause); }
0N/A * }
0N/A *
0N/A * class LowLevelException extends Exception {
0N/A * }
0N/A * </pre>
2548N/A * As of release 7, the platform supports the notion of
2548N/A * <i>suppressed exceptions</i> (in conjunction with automatic
2548N/A * resource management blocks). Any exceptions that were
2548N/A * suppressed in order to deliver an exception are printed out
2548N/A * beneath the stack trace. The format of this information
2548N/A * depends on the implementation, but the following example may be
2548N/A * regarded as typical:
2548N/A *
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Something happened
2548N/A * at Foo.bar(Foo.java:10)
2548N/A * at Foo.main(Foo.java:5)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 0
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo.bar(Foo.java:9)
2548N/A * ... 1 more
2548N/A * </pre>
2548N/A * Note that the "... n more" notation is used on suppressed exceptions
2548N/A * just at it is used on causes. Unlike causes, suppressed exceptions are
2548N/A * indented beyond their "containing exceptions."
2548N/A *
2548N/A * <p>An exception can have both a cause and one or more suppressed
2548N/A * exceptions:
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Main block
2548N/A * at Foo3.main(Foo3.java:7)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 2
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo3.main(Foo3.java:5)
2548N/A * Suppressed: Resource$CloseFailException: Resource ID = 1
2548N/A * at Resource.close(Resource.java:26)
2548N/A * at Foo3.main(Foo3.java:5)
2548N/A * Caused by: java.lang.Exception: I did it
2548N/A * at Foo3.main(Foo3.java:8)
2548N/A * </pre>
2548N/A * Likewise, a suppressed exception can have a cause:
2548N/A * <pre>
2548N/A * Exception in thread "main" java.lang.Exception: Main block
2548N/A * at Foo4.main(Foo4.java:6)
2548N/A * Suppressed: Resource2$CloseFailException: Resource ID = 1
2548N/A * at Resource2.close(Resource2.java:20)
2548N/A * at Foo4.main(Foo4.java:5)
2548N/A * Caused by: java.lang.Exception: Rats, you caught me
2548N/A * at Resource2$CloseFailException.<init>(Resource2.java:45)
2548N/A * ... 2 more
2548N/A * </pre>
0N/A */
0N/A public void printStackTrace() {
0N/A printStackTrace(System.err);
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the specified print stream.
0N/A *
2607N/A * @param s {@code PrintStream} to use for output
0N/A */
0N/A public void printStackTrace(PrintStream s) {
2548N/A printStackTrace(new WrappedPrintStream(s));
2548N/A }
2548N/A
2548N/A private void printStackTrace(PrintStreamOrWriter s) {
2607N/A // Guard against malicious overrides of Throwable.equals by
2607N/A // using a Set with identity equality semantics.
2607N/A Set<Throwable> dejaVu =
2607N/A Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
2548N/A dejaVu.add(this);
2548N/A
2548N/A synchronized (s.lock()) {
2548N/A // Print our stack trace
0N/A s.println(this);
0N/A StackTraceElement[] trace = getOurStackTrace();
2548N/A for (StackTraceElement traceElement : trace)
2548N/A s.println("\tat " + traceElement);
0N/A
2548N/A // Print suppressed exceptions, if any
2548N/A for (Throwable se : suppressedExceptions)
2548N/A se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
2548N/A
2548N/A // Print cause, if any
0N/A Throwable ourCause = getCause();
0N/A if (ourCause != null)
2548N/A ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
0N/A }
0N/A }
0N/A
0N/A /**
2548N/A * Print our stack trace as an enclosed exception for the specified
2548N/A * stack trace.
0N/A */
2548N/A private void printEnclosedStackTrace(PrintStreamOrWriter s,
2548N/A StackTraceElement[] enclosingTrace,
2548N/A String caption,
2548N/A String prefix,
2548N/A Set<Throwable> dejaVu) {
2548N/A assert Thread.holdsLock(s.lock());
2548N/A if (dejaVu.contains(this)) {
2548N/A s.println("\t[CIRCULAR REFERENCE:" + this + "]");
2548N/A } else {
2548N/A dejaVu.add(this);
2548N/A // Compute number of frames in common between this and enclosing trace
2548N/A StackTraceElement[] trace = getOurStackTrace();
2548N/A int m = trace.length - 1;
2548N/A int n = enclosingTrace.length - 1;
2548N/A while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
2548N/A m--; n--;
2548N/A }
2548N/A int framesInCommon = trace.length - 1 - m;
0N/A
2548N/A // Print our stack trace
2548N/A s.println(prefix + caption + this);
2548N/A for (int i = 0; i <= m; i++)
2548N/A s.println(prefix + "\tat " + trace[i]);
2548N/A if (framesInCommon != 0)
2548N/A s.println(prefix + "\t... " + framesInCommon + " more");
2548N/A
2548N/A // Print suppressed exceptions, if any
2548N/A for (Throwable se : suppressedExceptions)
2548N/A se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
2548N/A prefix +"\t", dejaVu);
2548N/A
2548N/A // Print cause, if any
2548N/A Throwable ourCause = getCause();
2548N/A if (ourCause != null)
2548N/A ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Prints this throwable and its backtrace to the specified
0N/A * print writer.
0N/A *
2607N/A * @param s {@code PrintWriter} to use for output
0N/A * @since JDK1.1
0N/A */
0N/A public void printStackTrace(PrintWriter s) {
2548N/A printStackTrace(new WrappedPrintWriter(s));
0N/A }
0N/A
0N/A /**
2548N/A * Wrapper class for PrintStream and PrintWriter to enable a single
2548N/A * implementation of printStackTrace.
0N/A */
2548N/A private abstract static class PrintStreamOrWriter {
2548N/A /** Returns the object to be locked when using this StreamOrWriter */
2548N/A abstract Object lock();
2548N/A
2548N/A /** Prints the specified string as a line on this StreamOrWriter */
2548N/A abstract void println(Object o);
2548N/A }
0N/A
2548N/A private static class WrappedPrintStream extends PrintStreamOrWriter {
2548N/A private final PrintStream printStream;
2548N/A
2548N/A WrappedPrintStream(PrintStream printStream) {
2548N/A this.printStream = printStream;
2548N/A }
2548N/A
2548N/A Object lock() {
2548N/A return printStream;
0N/A }
2548N/A
2548N/A void println(Object o) {
2548N/A printStream.println(o);
2548N/A }
2548N/A }
2548N/A
2548N/A private static class WrappedPrintWriter extends PrintStreamOrWriter {
2548N/A private final PrintWriter printWriter;
0N/A
2548N/A WrappedPrintWriter(PrintWriter printWriter) {
2548N/A this.printWriter = printWriter;
2548N/A }
0N/A
2548N/A Object lock() {
2548N/A return printWriter;
2548N/A }
2548N/A
2548N/A void println(Object o) {
2548N/A printWriter.println(o);
2548N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fills in the execution stack trace. This method records within this
2607N/A * {@code Throwable} object information about the current state of
0N/A * the stack frames for the current thread.
0N/A *
2607N/A * @return a reference to this {@code Throwable} instance.
0N/A * @see java.lang.Throwable#printStackTrace()
0N/A */
0N/A public synchronized native Throwable fillInStackTrace();
0N/A
0N/A /**
0N/A * Provides programmatic access to the stack trace information printed by
0N/A * {@link #printStackTrace()}. Returns an array of stack trace elements,
0N/A * each representing one stack frame. The zeroth element of the array
0N/A * (assuming the array's length is non-zero) represents the top of the
0N/A * stack, which is the last method invocation in the sequence. Typically,
0N/A * this is the point at which this throwable was created and thrown.
0N/A * The last element of the array (assuming the array's length is non-zero)
0N/A * represents the bottom of the stack, which is the first method invocation
0N/A * in the sequence.
0N/A *
0N/A * <p>Some virtual machines may, under some circumstances, omit one
0N/A * or more stack frames from the stack trace. In the extreme case,
0N/A * a virtual machine that has no stack trace information concerning
0N/A * this throwable is permitted to return a zero-length array from this
0N/A * method. Generally speaking, the array returned by this method will
0N/A * contain one element for every frame that would be printed by
2607N/A * {@code printStackTrace}.
0N/A *
0N/A * @return an array of stack trace elements representing the stack trace
0N/A * pertaining to this throwable.
0N/A * @since 1.4
0N/A */
0N/A public StackTraceElement[] getStackTrace() {
0N/A return getOurStackTrace().clone();
0N/A }
0N/A
0N/A private synchronized StackTraceElement[] getOurStackTrace() {
0N/A // Initialize stack trace if this is the first call to this method
0N/A if (stackTrace == null) {
0N/A int depth = getStackTraceDepth();
0N/A stackTrace = new StackTraceElement[depth];
0N/A for (int i=0; i < depth; i++)
0N/A stackTrace[i] = getStackTraceElement(i);
0N/A }
0N/A return stackTrace;
0N/A }
0N/A
0N/A /**
0N/A * Sets the stack trace elements that will be returned by
0N/A * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
0N/A * and related methods.
0N/A *
0N/A * This method, which is designed for use by RPC frameworks and other
0N/A * advanced systems, allows the client to override the default
0N/A * stack trace that is either generated by {@link #fillInStackTrace()}
0N/A * when a throwable is constructed or deserialized when a throwable is
0N/A * read from a serialization stream.
0N/A *
0N/A * @param stackTrace the stack trace elements to be associated with
2607N/A * this {@code Throwable}. The specified array is copied by this
0N/A * call; changes in the specified array after the method invocation
2607N/A * returns will have no affect on this {@code Throwable}'s stack
0N/A * trace.
0N/A *
2607N/A * @throws NullPointerException if {@code stackTrace} is
2607N/A * {@code null}, or if any of the elements of
2607N/A * {@code stackTrace} are {@code null}
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public void setStackTrace(StackTraceElement[] stackTrace) {
0N/A StackTraceElement[] defensiveCopy = stackTrace.clone();
0N/A for (int i = 0; i < defensiveCopy.length; i++)
0N/A if (defensiveCopy[i] == null)
0N/A throw new NullPointerException("stackTrace[" + i + "]");
0N/A
0N/A this.stackTrace = defensiveCopy;
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of elements in the stack trace (or 0 if the stack
0N/A * trace is unavailable).
1271N/A *
1271N/A * package-protection for use by SharedSecrets.
0N/A */
1271N/A native int getStackTraceDepth();
0N/A
0N/A /**
0N/A * Returns the specified element of the stack trace.
0N/A *
1271N/A * package-protection for use by SharedSecrets.
1271N/A *
0N/A * @param index index of the element to return.
2607N/A * @throws IndexOutOfBoundsException if {@code index < 0 ||
2607N/A * index >= getStackTraceDepth() }
0N/A */
1271N/A native StackTraceElement getStackTraceElement(int index);
0N/A
2548N/A private void readObject(ObjectInputStream s)
2548N/A throws IOException, ClassNotFoundException {
2548N/A s.defaultReadObject(); // read in all fields
2548N/A List<Throwable> suppressed = Collections.emptyList();
2548N/A if (suppressedExceptions != null &&
2548N/A !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
2548N/A suppressed = new ArrayList<Throwable>();
2548N/A for(Throwable t : suppressedExceptions) {
2548N/A if (t == null)
2548N/A throw new NullPointerException(NULL_CAUSE_MESSAGE);
2548N/A suppressed.add(t);
2548N/A }
2548N/A }
2548N/A suppressedExceptions = suppressed;
2548N/A }
2548N/A
2548N/A private synchronized void writeObject(ObjectOutputStream s)
0N/A throws IOException
0N/A {
0N/A getOurStackTrace(); // Ensure that stackTrace field is initialized.
0N/A s.defaultWriteObject();
0N/A }
2548N/A
2548N/A /**
2548N/A * Adds the specified exception to the list of exceptions that
2548N/A * were suppressed, typically by the automatic resource management
2548N/A * statement, in order to deliver this exception.
2548N/A *
2607N/A * <p>Note that when one exception {@linkplain
2607N/A * #initCause(Throwable) causes} another exception, the first
2607N/A * exception is usually caught and then the second exception is
2607N/A * thrown in response. In contrast, when one exception suppresses
2607N/A * another, two exceptions are thrown in sibling code blocks, such
2607N/A * as in a {@code try} block and in its {@code finally} block, and
2607N/A * control flow can only continue with one exception so the second
2607N/A * is recorded as a suppressed exception of the first.
2607N/A *
2548N/A * @param exception the exception to be added to the list of
2548N/A * suppressed exceptions
2548N/A * @throws NullPointerException if {@code exception} is null
2607N/A * @throws IllegalArgumentException if {@code exception} is this
2607N/A * throwable; a throwable cannot suppress itself.
2548N/A * @since 1.7
2548N/A */
2548N/A public synchronized void addSuppressedException(Throwable exception) {
2548N/A if (exception == null)
2548N/A throw new NullPointerException(NULL_CAUSE_MESSAGE);
2607N/A if (exception == this)
2607N/A throw new IllegalArgumentException("Self-suppression not permitted");
2548N/A
2548N/A if (suppressedExceptions.size() == 0)
2548N/A suppressedExceptions = new ArrayList<Throwable>();
2548N/A suppressedExceptions.add(exception);
2548N/A }
2548N/A
2548N/A private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
2548N/A
2548N/A /**
2548N/A * Returns an array containing all of the exceptions that were
2548N/A * suppressed, typically by the automatic resource management
2548N/A * statement, in order to deliver this exception.
2548N/A *
2548N/A * @return an array containing all of the exceptions that were
2548N/A * suppressed to deliver this exception.
2548N/A * @since 1.7
2548N/A */
2548N/A public Throwable[] getSuppressedExceptions() {
2548N/A return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
2548N/A }
0N/A}