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

Print this page


   1 /*
   2  * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any


 153  */
 154 public class Throwable implements Serializable {
 155     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 156     private static final long serialVersionUID = -3042686055658047285L;
 157 
 158     /**
 159      * Native code saves some indication of the stack backtrace in this slot.
 160      */
 161     private transient Object backtrace;
 162 
 163     /**
 164      * Specific details about the Throwable.  For example, for
 165      * {@code FileNotFoundException}, this contains the name of
 166      * the file that could not be found.
 167      *
 168      * @serial
 169      */
 170     private String detailMessage;
 171 
 172     /**









































 173      * The throwable that caused this throwable to get thrown, or null if this
 174      * throwable was not caused by another throwable, or if the causative
 175      * throwable is unknown.  If this field is equal to this throwable itself,
 176      * it indicates that the cause of this throwable has not yet been
 177      * initialized.
 178      *
 179      * @serial
 180      * @since 1.4
 181      */
 182     private Throwable cause = this;
 183 
 184     /**
 185      * The stack trace, as returned by {@link #getStackTrace()}.
 186      *
 187      * @serial
 188      * @since 1.4
 189      */
 190     private StackTraceElement[] stackTrace;
 191     /*
 192      * This field is lazily initialized on first use or serialization and
 193      * nulled out when fillInStackTrace is called.
 194      */
 195 





 196     /**
 197      * The list of suppressed exceptions, as returned by
 198      * {@link #getSuppressedExceptions()}.



 199      *
 200      * @serial
 201      * @since 1.7
 202      */
 203     private List<Throwable> suppressedExceptions = null;
 204     /*
 205      * This field is lazily initialized when the first suppressed
 206      * exception is added.
 207      *
 208      * OutOfMemoryError is preallocated in the VM for better OOM
 209      * diagnosability during VM initialization. Constructor can't
 210      * be not invoked. If a new field to be added in the future must
 211      * be initialized to non-null, it requires a synchronized VM change.
 212      */
 213 
 214     /** Message for trying to suppress a null exception. */
 215     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 216 



 217     /** Caption  for labeling causative exception stack traces */
 218     private static final String CAUSE_CAPTION = "Caused by: ";
 219 
 220     /** Caption for labeling suppressed exception stack traces */
 221     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 222 
 223     /**
 224      * Constructs a new throwable with {@code null} as its detail message.
 225      * The cause is not initialized, and may subsequently be initialized by a
 226      * call to {@link #initCause}.
 227      *
 228      * <p>The {@link #fillInStackTrace()} method is called to initialize
 229      * the stack trace data in the newly created throwable.
 230      */
 231     public Throwable() {
 232         fillInStackTrace();
 233     }
 234 
 235     /**
 236      * Constructs a new throwable with the specified detail message.  The


 555      */
 556     public void printStackTrace(PrintStream s) {
 557         printStackTrace(new WrappedPrintStream(s));
 558     }
 559 
 560     private void printStackTrace(PrintStreamOrWriter s) {
 561         // Guard against malicious overrides of Throwable.equals by
 562         // using a Set with identity equality semantics.
 563         Set<Throwable> dejaVu =
 564             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
 565         dejaVu.add(this);
 566 
 567         synchronized (s.lock()) {
 568             // Print our stack trace
 569             s.println(this);
 570             StackTraceElement[] trace = getOurStackTrace();
 571             for (StackTraceElement traceElement : trace)
 572                 s.println("\tat " + traceElement);
 573 
 574             // Print suppressed exceptions, if any
 575             for (Throwable se : getSuppressedExceptions())
 576                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 577 
 578             // Print cause, if any
 579             Throwable ourCause = getCause();
 580             if (ourCause != null)
 581                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 582         }
 583     }
 584 
 585     /**
 586      * Print our stack trace as an enclosed exception for the specified
 587      * stack trace.
 588      */
 589     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 590                                          StackTraceElement[] enclosingTrace,
 591                                          String caption,
 592                                          String prefix,
 593                                          Set<Throwable> dejaVu) {
 594         assert Thread.holdsLock(s.lock());
 595         if (dejaVu.contains(this)) {
 596             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
 597         } else {
 598             dejaVu.add(this);
 599             // Compute number of frames in common between this and enclosing trace
 600             StackTraceElement[] trace = getOurStackTrace();
 601             int m = trace.length - 1;
 602             int n = enclosingTrace.length - 1;
 603             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 604                 m--; n--;
 605             }
 606             int framesInCommon = trace.length - 1 - m;
 607 
 608             // Print our stack trace
 609             s.println(prefix + caption + this);
 610             for (int i = 0; i <= m; i++)
 611                 s.println(prefix + "\tat " + trace[i]);
 612             if (framesInCommon != 0)
 613                 s.println(prefix + "\t... " + framesInCommon + " more");
 614 
 615             // Print suppressed exceptions, if any
 616             for (Throwable se : getSuppressedExceptions())
 617                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 618                                            prefix +"\t", dejaVu);
 619 
 620             // Print cause, if any
 621             Throwable ourCause = getCause();
 622             if (ourCause != null)
 623                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 624         }
 625     }
 626 
 627     /**
 628      * Prints this throwable and its backtrace to the specified
 629      * print writer.
 630      *
 631      * @param s {@code PrintWriter} to use for output
 632      * @since   JDK1.1
 633      */
 634     public void printStackTrace(PrintWriter s) {
 635         printStackTrace(new WrappedPrintWriter(s));
 636     }


 701      * in the sequence.
 702      *
 703      * <p>Some virtual machines may, under some circumstances, omit one
 704      * or more stack frames from the stack trace.  In the extreme case,
 705      * a virtual machine that has no stack trace information concerning
 706      * this throwable is permitted to return a zero-length array from this
 707      * method.  Generally speaking, the array returned by this method will
 708      * contain one element for every frame that would be printed by
 709      * {@code printStackTrace}.
 710      *
 711      * @return an array of stack trace elements representing the stack trace
 712      *         pertaining to this throwable.
 713      * @since  1.4
 714      */
 715     public StackTraceElement[] getStackTrace() {
 716         return getOurStackTrace().clone();
 717     }
 718 
 719     private synchronized StackTraceElement[] getOurStackTrace() {
 720         // Initialize stack trace if this is the first call to this method
 721         if (stackTrace == null) {
 722             int depth = getStackTraceDepth();
 723             stackTrace = new StackTraceElement[depth];
 724             for (int i=0; i < depth; i++)
 725                 stackTrace[i] = getStackTraceElement(i);


 726         }

 727         return stackTrace;
 728     }
 729 
 730     /**
 731      * Sets the stack trace elements that will be returned by
 732      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 733      * and related methods.
 734      *
 735      * This method, which is designed for use by RPC frameworks and other
 736      * advanced systems, allows the client to override the default
 737      * stack trace that is either generated by {@link #fillInStackTrace()}
 738      * when a throwable is constructed or deserialized when a throwable is
 739      * read from a serialization stream.
 740      *





 741      * @param   stackTrace the stack trace elements to be associated with
 742      * this {@code Throwable}.  The specified array is copied by this
 743      * call; changes in the specified array after the method invocation
 744      * returns will have no affect on this {@code Throwable}'s stack
 745      * trace.
 746      *
 747      * @throws NullPointerException if {@code stackTrace} is
 748      *         {@code null}, or if any of the elements of
 749      *         {@code stackTrace} are {@code null}
 750      *
 751      * @since  1.4
 752      */
 753     public void setStackTrace(StackTraceElement[] stackTrace) {

 754         StackTraceElement[] defensiveCopy = stackTrace.clone();








 755         for (int i = 0; i < defensiveCopy.length; i++)
 756             if (defensiveCopy[i] == null)
 757                 throw new NullPointerException("stackTrace[" + i + "]");

 758 
 759         synchronized (this) {
 760             this.stackTrace = defensiveCopy;
 761         }
 762     }
 763 
 764     /**
 765      * Returns the number of elements in the stack trace (or 0 if the stack
 766      * trace is unavailable).
 767      *
 768      * package-protection for use by SharedSecrets.
 769      */
 770     native int getStackTraceDepth();
 771 
 772     /**
 773      * Returns the specified element of the stack trace.
 774      *
 775      * package-protection for use by SharedSecrets.
 776      *
 777      * @param index index of the element to return.
 778      * @throws IndexOutOfBoundsException if {@code index < 0 ||
 779      *         index >= getStackTraceDepth() }
 780      */
 781     native StackTraceElement getStackTraceElement(int index);
 782 
 783     private void readObject(ObjectInputStream s)
 784         throws IOException, ClassNotFoundException {
 785         s.defaultReadObject();     // read in all fields
 786         List<Throwable> suppressed = null;
 787         if (suppressedExceptions != null &&
 788             !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
 789             suppressed = new ArrayList<Throwable>();
 790             for (Throwable t : suppressedExceptions) {


 791                 if (t == null)
 792                     throw new NullPointerException(NULL_CAUSE_MESSAGE);


 793                 suppressed.add(t);
 794             }
 795         }






 796         suppressedExceptions = suppressed;







 797     }
 798 
 799     private synchronized void writeObject(ObjectOutputStream s)
 800         throws IOException
 801     {
 802         getOurStackTrace();  // Ensure that stackTrace field is initialized.



 803         s.defaultWriteObject();
 804     }
 805 
 806     /**
 807      * Adds the specified exception to the list of exceptions that
 808      * were suppressed, typically by the {@code try}-with-resources
 809      * statement, in order to deliver this exception.
 810      *








 811      * <p>Note that when one exception {@linkplain
 812      * #initCause(Throwable) causes} another exception, the first
 813      * exception is usually caught and then the second exception is
 814      * thrown in response.  In contrast, when one exception suppresses
 815      * another, two exceptions are thrown in sibling code blocks, such
 816      * as in a {@code try} block and in its {@code finally} block, and
 817      * control flow can only continue with one exception so the second
 818      * is recorded as a suppressed exception of the first.
 819      *
 820      * @param exception the exception to be added to the list of
 821      *        suppressed exceptions
 822      * @throws NullPointerException if {@code exception} is null
 823      * @throws IllegalArgumentException if {@code exception} is this
 824      *         throwable; a throwable cannot suppress itself.


 825      * @since 1.7
 826      */
 827     public synchronized void addSuppressedException(Throwable exception) {
 828         if (exception == null)
 829             throw new NullPointerException(NULL_CAUSE_MESSAGE);
 830         if (exception == this)
 831             throw new IllegalArgumentException("Self-suppression not permitted");

















 832 
 833         if (suppressedExceptions == null)
 834             suppressedExceptions = new ArrayList<Throwable>();
 835         suppressedExceptions.add(exception);
 836     }

 837 
 838     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 839 
 840     /**
 841      * Returns an array containing all of the exceptions that were
 842      * suppressed, typically by the {@code try}-with-resources
 843      * statement, in order to deliver this exception.
 844      *


 845      * @return an array containing all of the exceptions that were
 846      *         suppressed to deliver this exception.
 847      * @since 1.7
 848      */
 849     public synchronized Throwable[] getSuppressedExceptions() {
 850         if (suppressedExceptions == null)

 851             return EMPTY_THROWABLE_ARRAY;
 852         else
 853             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 854     }
 855 }
   1 /*
   2  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any


 153  */
 154 public class Throwable implements Serializable {
 155     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 156     private static final long serialVersionUID = -3042686055658047285L;
 157 
 158     /**
 159      * Native code saves some indication of the stack backtrace in this slot.
 160      */
 161     private transient Object backtrace;
 162 
 163     /**
 164      * Specific details about the Throwable.  For example, for
 165      * {@code FileNotFoundException}, this contains the name of
 166      * the file that could not be found.
 167      *
 168      * @serial
 169      */
 170     private String detailMessage;
 171 
 172     /**
 173      * {@linkplain #setStackTrace(StackTraceElement[] Setting the
 174      * stack trace} to a one-element array containing this sentinel
 175      * value indicates future attempts to set the stack trace will be
 176      * ignored.  The sentinal is equal to the result of calling:<br>
 177      * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
 178      */
 179     public static final StackTraceElement STACK_TRACE_SENTINEL =
 180         new StackTraceElement("", "", null, Integer.MIN_VALUE);
 181 
 182     /**
 183      * A value indicating the stack trace field has not yet been initialized.
 184      */
 185     private static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0];
 186 
 187     /*
 188      * To allow Throwable objects to be made immutable and safely
 189      * reused by the JVM, such as OutOfMemoryErrors, the three fields
 190      * of Throwable that are writable in response to user actions,
 191      * cause, stackTrace, and suppressedExceptions obey the following
 192      * protocol:
 193      *
 194      * 1) The fields are initialized to a non-null sentinel value
 195      * which indicates the value has logically not been set.
 196      *
 197      * 2) Writing a null to the field indicates further writes
 198      * are forbidden
 199      * 
 200      * 3) The sentinel value may be replaced with another non-null
 201      * value.
 202      *
 203      * For example, implementations of the HotSpot JVM have
 204      * preallocated OutOfMemoryError objects to provide for better
 205      * diagnosability of that situation.  These objects are created
 206      * without calling the constructor for that class and the fields
 207      * in question are initialized to null.  To support this
 208      * capability, any new fields added to Throwable that require
 209      * being initialized to a non-null value require a coordinated JVM
 210      * change.
 211      */
 212 
 213     /**
 214      * The throwable that caused this throwable to get thrown, or null if this
 215      * throwable was not caused by another throwable, or if the causative
 216      * throwable is unknown.  If this field is equal to this throwable itself,
 217      * it indicates that the cause of this throwable has not yet been
 218      * initialized.
 219      *
 220      * @serial
 221      * @since 1.4
 222      */
 223     private Throwable cause = this;
 224 
 225     /**
 226      * The stack trace, as returned by {@link #getStackTrace()}.
 227      *
 228      * @serial
 229      * @since 1.4
 230      */
 231     private StackTraceElement[] stackTrace = new StackTraceElement[0];
 232     /*
 233      * This field above is lazily initialized on first use or
 234      * serialization and nulled out when fillInStackTrace is called.
 235      */
 236 
 237     // Setting this static field introduces an acceptable
 238     // initialization dependency on a few java.util classes.
 239     private static final List<Throwable> suppressedSentinel =
 240         Collections.unmodifiableList(new ArrayList<Throwable>(0));
 241 
 242     /**
 243      * The list of suppressed exceptions, as returned by {@link
 244      * #getSuppressed()}.  The list is initialized to a zero-element
 245      * unmodifiable sentinel list.  When a serialized Throwable is
 246      * read in, if the {@code suppressedExceptions} field points to a
 247      * zero-element list, the field is reset to the sentinel value.
 248      *
 249      * @serial
 250      * @since 1.7
 251      */
 252     private List<Throwable> suppressedExceptions = suppressedSentinel;









 253 
 254     /** Message for trying to suppress a null exception. */
 255     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
 256 
 257     /** Message for trying to suppress oneself. */
 258     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
 259 
 260     /** Caption  for labeling causative exception stack traces */
 261     private static final String CAUSE_CAPTION = "Caused by: ";
 262 
 263     /** Caption for labeling suppressed exception stack traces */
 264     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
 265 
 266     /**
 267      * Constructs a new throwable with {@code null} as its detail message.
 268      * The cause is not initialized, and may subsequently be initialized by a
 269      * call to {@link #initCause}.
 270      *
 271      * <p>The {@link #fillInStackTrace()} method is called to initialize
 272      * the stack trace data in the newly created throwable.
 273      */
 274     public Throwable() {
 275         fillInStackTrace();
 276     }
 277 
 278     /**
 279      * Constructs a new throwable with the specified detail message.  The


 598      */
 599     public void printStackTrace(PrintStream s) {
 600         printStackTrace(new WrappedPrintStream(s));
 601     }
 602 
 603     private void printStackTrace(PrintStreamOrWriter s) {
 604         // Guard against malicious overrides of Throwable.equals by
 605         // using a Set with identity equality semantics.
 606         Set<Throwable> dejaVu =
 607             Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
 608         dejaVu.add(this);
 609 
 610         synchronized (s.lock()) {
 611             // Print our stack trace
 612             s.println(this);
 613             StackTraceElement[] trace = getOurStackTrace();
 614             for (StackTraceElement traceElement : trace)
 615                 s.println("\tat " + traceElement);
 616 
 617             // Print suppressed exceptions, if any
 618             for (Throwable se : getSuppressed())
 619                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
 620 
 621             // Print cause, if any
 622             Throwable ourCause = getCause();
 623             if (ourCause != null)
 624                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
 625         }
 626     }
 627 
 628     /**
 629      * Print our stack trace as an enclosed exception for the specified
 630      * stack trace.
 631      */
 632     private void printEnclosedStackTrace(PrintStreamOrWriter s,
 633                                          StackTraceElement[] enclosingTrace,
 634                                          String caption,
 635                                          String prefix,
 636                                          Set<Throwable> dejaVu) {
 637         assert Thread.holdsLock(s.lock());
 638         if (dejaVu.contains(this)) {
 639             s.println("\t[CIRCULAR REFERENCE:" + this + "]");
 640         } else {
 641             dejaVu.add(this);
 642             // Compute number of frames in common between this and enclosing trace
 643             StackTraceElement[] trace = getOurStackTrace();
 644             int m = trace.length - 1;
 645             int n = enclosingTrace.length - 1;
 646             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
 647                 m--; n--;
 648             }
 649             int framesInCommon = trace.length - 1 - m;
 650 
 651             // Print our stack trace
 652             s.println(prefix + caption + this);
 653             for (int i = 0; i <= m; i++)
 654                 s.println(prefix + "\tat " + trace[i]);
 655             if (framesInCommon != 0)
 656                 s.println(prefix + "\t... " + framesInCommon + " more");
 657 
 658             // Print suppressed exceptions, if any
 659             for (Throwable se : getSuppressed())
 660                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
 661                                            prefix +"\t", dejaVu);
 662 
 663             // Print cause, if any
 664             Throwable ourCause = getCause();
 665             if (ourCause != null)
 666                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
 667         }
 668     }
 669 
 670     /**
 671      * Prints this throwable and its backtrace to the specified
 672      * print writer.
 673      *
 674      * @param s {@code PrintWriter} to use for output
 675      * @since   JDK1.1
 676      */
 677     public void printStackTrace(PrintWriter s) {
 678         printStackTrace(new WrappedPrintWriter(s));
 679     }


 744      * in the sequence.
 745      *
 746      * <p>Some virtual machines may, under some circumstances, omit one
 747      * or more stack frames from the stack trace.  In the extreme case,
 748      * a virtual machine that has no stack trace information concerning
 749      * this throwable is permitted to return a zero-length array from this
 750      * method.  Generally speaking, the array returned by this method will
 751      * contain one element for every frame that would be printed by
 752      * {@code printStackTrace}.
 753      *
 754      * @return an array of stack trace elements representing the stack trace
 755      *         pertaining to this throwable.
 756      * @since  1.4
 757      */
 758     public StackTraceElement[] getStackTrace() {
 759         return getOurStackTrace().clone();
 760     }
 761 
 762     private synchronized StackTraceElement[] getOurStackTrace() {
 763         // Initialize stack trace if this is the first call to this method
 764         if (stackTrace == EMPTY_STACK) {
 765             int depth = getStackTraceDepth();
 766             stackTrace = new StackTraceElement[depth];
 767             for (int i=0; i < depth; i++)
 768                 stackTrace[i] = getStackTraceElement(i);
 769         } else if  (stackTrace == null) {
 770             return EMPTY_STACK;
 771         }
 772 
 773         return stackTrace;
 774     }
 775 
 776     /**
 777      * Sets the stack trace elements that will be returned by
 778      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
 779      * and related methods.
 780      *
 781      * This method, which is designed for use by RPC frameworks and other
 782      * advanced systems, allows the client to override the default
 783      * stack trace that is either generated by {@link #fillInStackTrace()}
 784      * when a throwable is constructed or deserialized when a throwable is
 785      * read from a serialization stream.
 786      *
 787      * <p>If the stack trace is set to one-element array containing
 788      * the {@linkplain #STACK_TRACE_SENTINEL stack trace sentinel}
 789      * value, then future calls to this method have no effect other
 790      * than validating the argument is non-null.
 791      *
 792      * @param   stackTrace the stack trace elements to be associated with
 793      * this {@code Throwable}.  The specified array is copied by this
 794      * call; changes in the specified array after the method invocation
 795      * returns will have no affect on this {@code Throwable}'s stack
 796      * trace.
 797      *
 798      * @throws NullPointerException if {@code stackTrace} is
 799      *         {@code null}, or if any of the elements of
 800      *         {@code stackTrace} are {@code null}
 801      *
 802      * @since  1.4
 803      */
 804     public void setStackTrace(StackTraceElement[] stackTrace) {
 805         // Null-check the argument
 806         StackTraceElement[] defensiveCopy = stackTrace.clone();
 807 
 808         if (stackTrace == null)
 809             return;
 810 
 811         if (defensiveCopy.length == 1 &&
 812             STACK_TRACE_SENTINEL.equals(defensiveCopy[0]))
 813             defensiveCopy = null;
 814         else {
 815             for (int i = 0; i < defensiveCopy.length; i++)
 816                 if (defensiveCopy[i] == null)
 817                     throw new NullPointerException("stackTrace[" + i + "]");
 818         }
 819         
 820         synchronized (this) {
 821             this.stackTrace = defensiveCopy;
 822         }
 823     }
 824 
 825     /**
 826      * Returns the number of elements in the stack trace (or 0 if the stack
 827      * trace is unavailable).
 828      *
 829      * package-protection for use by SharedSecrets.
 830      */
 831     native int getStackTraceDepth();
 832 
 833     /**
 834      * Returns the specified element of the stack trace.
 835      *
 836      * package-protection for use by SharedSecrets.
 837      *
 838      * @param index index of the element to return.
 839      * @throws IndexOutOfBoundsException if {@code index < 0 ||
 840      *         index >= getStackTraceDepth() }
 841      */
 842     native StackTraceElement getStackTraceElement(int index);
 843 
 844     private void readObject(ObjectInputStream s)
 845         throws IOException, ClassNotFoundException {
 846         s.defaultReadObject();     // read in all fields
 847         List<Throwable> suppressed = null;
 848         if (suppressedExceptions != null &&
 849             !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
 850             suppressed = new ArrayList<Throwable>(1);
 851             for (Throwable t : suppressedExceptions) {
 852                 // Enforce constraints on suppressed exceptions in
 853                 // case of corrupt or malicious stream.
 854                 if (t == null)
 855                     throw new NullPointerException(NULL_CAUSE_MESSAGE);
 856                 if (t == this)
 857                     throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 858                 suppressed.add(t);
 859             }
 860         }
 861 
 862         // If suppressed is a zero-length list, use the sentinel
 863         // value.
 864         if (suppressed != null && suppressed.isEmpty())
 865             suppressedExceptions = suppressedSentinel;
 866         else
 867             suppressedExceptions = suppressed;
 868 
 869         // Note that there are no constraints on the value the cause
 870         // field can hold; both null and this are valid values for the
 871         // field.
 872 
 873         // Also note that a null stack trace indicates calls to
 874         // setStackTrace do not set the stack trace.
 875     }
 876 
 877     private synchronized void writeObject(ObjectOutputStream s)
 878         throws IOException {
 879         // Ensure that the stackTrace field is initialized to a
 880         // non-null value, if appropriate.  As of JDK 7, a null stack
 881         // trace field is a valid value indicating the stack trace
 882         // should not be set.
 883         getOurStackTrace();  
 884         s.defaultWriteObject();
 885     }
 886 
 887     /**
 888      * Adds the specified exception to the list of exceptions that
 889      * were suppressed, typically by the {@code try}-with-resources
 890      * statement, in order to deliver this exception.
 891      *
 892      * If the first exception to be suppressed is {@code null}, that
 893      * indicates suppressed exception information will <em>not</em> be
 894      * recorded for this exception.  Subsequent calls to this method
 895      * will not record any suppressed exceptions.  Otherwise,
 896      * attempting to suppress {@code null} after an exception has
 897      * already been successfully suppressed results in a {@code
 898      * NullPointerException}.
 899      *
 900      * <p>Note that when one exception {@linkplain
 901      * #initCause(Throwable) causes} another exception, the first
 902      * exception is usually caught and then the second exception is
 903      * thrown in response.  In contrast, when one exception suppresses
 904      * another, two exceptions are thrown in sibling code blocks, such
 905      * as in a {@code try} block and in its {@code finally} block, and
 906      * control flow can only continue with one exception so the second
 907      * is recorded as a suppressed exception of the first.
 908      *
 909      * @param exception the exception to be added to the list of
 910      *        suppressed exceptions

 911      * @throws IllegalArgumentException if {@code exception} is this
 912      *         throwable; a throwable cannot suppress itself.
 913      * @throws NullPointerException if {@code exception} is null and
 914      *         an exception has already been suppressed by this exception
 915      * @since 1.7
 916      */
 917     public synchronized void addSuppressed(Throwable exception) {


 918         if (exception == this)
 919             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
 920 
 921         if (exception == null) {
 922             if (suppressedExceptions == suppressedSentinel) {
 923                 suppressedExceptions = null; // No suppression information recorded
 924                 return;
 925             } else
 926                 throw new NullPointerException(NULL_CAUSE_MESSAGE);
 927         } else {
 928             assert exception != null && exception != this;
 929 
 930             if (suppressedExceptions == null) // Suppressed exceptions not recorded
 931                 return;
 932 
 933             if (suppressedExceptions == suppressedSentinel)
 934                 suppressedExceptions = new ArrayList<Throwable>(1);
 935 
 936             assert suppressedExceptions != suppressedSentinel;
 937 


 938             suppressedExceptions.add(exception);
 939         }
 940     }
 941 
 942     private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
 943 
 944     /**
 945      * Returns an array containing all of the exceptions that were
 946      * suppressed, typically by the {@code try}-with-resources
 947      * statement, in order to deliver this exception.
 948      *
 949      * If no exceptions were suppressed, an empty array is returned.
 950      *
 951      * @return an array containing all of the exceptions that were
 952      *         suppressed to deliver this exception.
 953      * @since 1.7
 954      */
 955     public synchronized Throwable[] getSuppressed() {
 956         if (suppressedExceptions == suppressedSentinel ||
 957             suppressedExceptions == null)
 958             return EMPTY_THROWABLE_ARRAY;
 959         else
 960             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
 961     }
 962 }