Save This Page
Home » openjdk-7 » java » lang » [javadoc | source]
    1   /*
    2    * Copyright 1994-2006 Sun Microsystems, Inc.  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.  Sun designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   22    * CA 95054 USA or visit www.sun.com if you need additional information or
   23    * have any questions.
   24    */
   25   
   26   package java.lang;
   27   import java.io;
   28   
   29   /**
   30    * The <code>Throwable</code> class is the superclass of all errors and
   31    * exceptions in the Java language. Only objects that are instances of this
   32    * class (or one of its subclasses) are thrown by the Java Virtual Machine or
   33    * can be thrown by the Java <code>throw</code> statement. Similarly, only
   34    * this class or one of its subclasses can be the argument type in a
   35    * <code>catch</code> clause.
   36    *
   37    * <p>Instances of two subclasses, {@link java.lang.Error} and
   38    * {@link java.lang.Exception}, are conventionally used to indicate
   39    * that exceptional situations have occurred. Typically, these instances
   40    * are freshly created in the context of the exceptional situation so
   41    * as to include relevant information (such as stack trace data).
   42    *
   43    * <p>A throwable contains a snapshot of the execution stack of its thread at
   44    * the time it was created. It can also contain a message string that gives
   45    * more information about the error. Finally, it can contain a <i>cause</i>:
   46    * another throwable that caused this throwable to get thrown.  The cause
   47    * facility is new in release 1.4.  It is also known as the <i>chained
   48    * exception</i> facility, as the cause can, itself, have a cause, and so on,
   49    * leading to a "chain" of exceptions, each caused by another.
   50    *
   51    * <p>One reason that a throwable may have a cause is that the class that
   52    * throws it is built atop a lower layered abstraction, and an operation on
   53    * the upper layer fails due to a failure in the lower layer.  It would be bad
   54    * design to let the throwable thrown by the lower layer propagate outward, as
   55    * it is generally unrelated to the abstraction provided by the upper layer.
   56    * Further, doing so would tie the API of the upper layer to the details of
   57    * its implementation, assuming the lower layer's exception was a checked
   58    * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
   59    * cause) allows the upper layer to communicate the details of the failure to
   60    * its caller without incurring either of these shortcomings.  It preserves
   61    * the flexibility to change the implementation of the upper layer without
   62    * changing its API (in particular, the set of exceptions thrown by its
   63    * methods).
   64    *
   65    * <p>A second reason that a throwable may have a cause is that the method
   66    * that throws it must conform to a general-purpose interface that does not
   67    * permit the method to throw the cause directly.  For example, suppose
   68    * a persistent collection conforms to the {@link java.util.Collection
   69    * Collection} interface, and that its persistence is implemented atop
   70    * <tt>java.io</tt>.  Suppose the internals of the <tt>add</tt> method
   71    * can throw an {@link java.io.IOException IOException}.  The implementation
   72    * can communicate the details of the <tt>IOException</tt> to its caller
   73    * while conforming to the <tt>Collection</tt> interface by wrapping the
   74    * <tt>IOException</tt> in an appropriate unchecked exception.  (The
   75    * specification for the persistent collection should indicate that it is
   76    * capable of throwing such exceptions.)
   77    *
   78    * <p>A cause can be associated with a throwable in two ways: via a
   79    * constructor that takes the cause as an argument, or via the
   80    * {@link #initCause(Throwable)} method.  New throwable classes that
   81    * wish to allow causes to be associated with them should provide constructors
   82    * that take a cause and delegate (perhaps indirectly) to one of the
   83    * <tt>Throwable</tt> constructors that takes a cause.  For example:
   84    * <pre>
   85    *     try {
   86    *         lowLevelOp();
   87    *     } catch (LowLevelException le) {
   88    *         throw new HighLevelException(le);  // Chaining-aware constructor
   89    *     }
   90    * </pre>
   91    * Because the <tt>initCause</tt> method is public, it allows a cause to be
   92    * associated with any throwable, even a "legacy throwable" whose
   93    * implementation predates the addition of the exception chaining mechanism to
   94    * <tt>Throwable</tt>. For example:
   95    * <pre>
   96    *     try {
   97    *         lowLevelOp();
   98    *     } catch (LowLevelException le) {
   99    *         throw (HighLevelException)
  100                    new HighLevelException().initCause(le);  // Legacy constructor
  101    *     }
  102    * </pre>
  103    *
  104    * <p>Prior to release 1.4, there were many throwables that had their own
  105    * non-standard exception chaining mechanisms (
  106    * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
  107    * {@link java.lang.reflect.UndeclaredThrowableException},
  108    * {@link java.lang.reflect.InvocationTargetException},
  109    * {@link java.io.WriteAbortedException},
  110    * {@link java.security.PrivilegedActionException},
  111    * {@link java.awt.print.PrinterIOException},
  112    * {@link java.rmi.RemoteException} and
  113    * {@link javax.naming.NamingException}).
  114    * All of these throwables have been retrofitted to
  115    * use the standard exception chaining mechanism, while continuing to
  116    * implement their "legacy" chaining mechanisms for compatibility.
  117    *
  118    * <p>Further, as of release 1.4, many general purpose <tt>Throwable</tt>
  119    * classes (for example {@link Exception}, {@link RuntimeException},
  120    * {@link Error}) have been retrofitted with constructors that take
  121    * a cause.  This was not strictly necessary, due to the existence of the
  122    * <tt>initCause</tt> method, but it is more convenient and expressive to
  123    * delegate to a constructor that takes a cause.
  124    *
  125    * <p>By convention, class <code>Throwable</code> and its subclasses have two
  126    * constructors, one that takes no arguments and one that takes a
  127    * <code>String</code> argument that can be used to produce a detail message.
  128    * Further, those subclasses that might likely have a cause associated with
  129    * them should have two more constructors, one that takes a
  130    * <code>Throwable</code> (the cause), and one that takes a
  131    * <code>String</code> (the detail message) and a <code>Throwable</code> (the
  132    * cause).
  133    *
  134    * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
  135    * which allows programmatic access to the stack trace information that was
  136    * previously available only in text form, via the various forms of the
  137    * {@link #printStackTrace()} method.  This information has been added to the
  138    * <i>serialized representation</i> of this class so <tt>getStackTrace</tt>
  139    * and <tt>printStackTrace</tt> will operate properly on a throwable that
  140    * was obtained by deserialization.
  141    *
  142    * @author  unascribed
  143    * @author  Josh Bloch (Added exception chaining and programmatic access to
  144    *          stack trace in 1.4.)
  145    * @since JDK1.0
  146    */
  147   public class Throwable implements Serializable {
  148       /** use serialVersionUID from JDK 1.0.2 for interoperability */
  149       private static final long serialVersionUID = -3042686055658047285L;
  150   
  151       /**
  152        * Native code saves some indication of the stack backtrace in this slot.
  153        */
  154       private transient Object backtrace;
  155   
  156       /**
  157        * Specific details about the Throwable.  For example, for
  158        * <tt>FileNotFoundException</tt>, this contains the name of
  159        * the file that could not be found.
  160        *
  161        * @serial
  162        */
  163       private String detailMessage;
  164   
  165       /**
  166        * The throwable that caused this throwable to get thrown, or null if this
  167        * throwable was not caused by another throwable, or if the causative
  168        * throwable is unknown.  If this field is equal to this throwable itself,
  169        * it indicates that the cause of this throwable has not yet been
  170        * initialized.
  171        *
  172        * @serial
  173        * @since 1.4
  174        */
  175       private Throwable cause = this;
  176   
  177       /**
  178        * The stack trace, as returned by {@link #getStackTrace()}.
  179        *
  180        * @serial
  181        * @since 1.4
  182        */
  183       private StackTraceElement[] stackTrace;
  184       /*
  185        * This field is lazily initialized on first use or serialization and
  186        * nulled out when fillInStackTrace is called.
  187        */
  188   
  189       /**
  190        * Constructs a new throwable with <code>null</code> as its detail message.
  191        * The cause is not initialized, and may subsequently be initialized by a
  192        * call to {@link #initCause}.
  193        *
  194        * <p>The {@link #fillInStackTrace()} method is called to initialize
  195        * the stack trace data in the newly created throwable.
  196        */
  197       public Throwable() {
  198           fillInStackTrace();
  199       }
  200   
  201       /**
  202        * Constructs a new throwable with the specified detail message.  The
  203        * cause is not initialized, and may subsequently be initialized by
  204        * a call to {@link #initCause}.
  205        *
  206        * <p>The {@link #fillInStackTrace()} method is called to initialize
  207        * the stack trace data in the newly created throwable.
  208        *
  209        * @param   message   the detail message. The detail message is saved for
  210        *          later retrieval by the {@link #getMessage()} method.
  211        */
  212       public Throwable(String message) {
  213           fillInStackTrace();
  214           detailMessage = message;
  215       }
  216   
  217       /**
  218        * Constructs a new throwable with the specified detail message and
  219        * cause.  <p>Note that the detail message associated with
  220        * <code>cause</code> is <i>not</i> automatically incorporated in
  221        * this throwable's detail message.
  222        *
  223        * <p>The {@link #fillInStackTrace()} method is called to initialize
  224        * the stack trace data in the newly created throwable.
  225        *
  226        * @param  message the detail message (which is saved for later retrieval
  227        *         by the {@link #getMessage()} method).
  228        * @param  cause the cause (which is saved for later retrieval by the
  229        *         {@link #getCause()} method).  (A <tt>null</tt> value is
  230        *         permitted, and indicates that the cause is nonexistent or
  231        *         unknown.)
  232        * @since  1.4
  233        */
  234       public Throwable(String message, Throwable cause) {
  235           fillInStackTrace();
  236           detailMessage = message;
  237           this.cause = cause;
  238       }
  239   
  240       /**
  241        * Constructs a new throwable with the specified cause and a detail
  242        * message of <tt>(cause==null ? null : cause.toString())</tt> (which
  243        * typically contains the class and detail message of <tt>cause</tt>).
  244        * This constructor is useful for throwables that are little more than
  245        * wrappers for other throwables (for example, {@link
  246        * java.security.PrivilegedActionException}).
  247        *
  248        * <p>The {@link #fillInStackTrace()} method is called to initialize
  249        * the stack trace data in the newly created throwable.
  250        *
  251        * @param  cause the cause (which is saved for later retrieval by the
  252        *         {@link #getCause()} method).  (A <tt>null</tt> value is
  253        *         permitted, and indicates that the cause is nonexistent or
  254        *         unknown.)
  255        * @since  1.4
  256        */
  257       public Throwable(Throwable cause) {
  258           fillInStackTrace();
  259           detailMessage = (cause==null ? null : cause.toString());
  260           this.cause = cause;
  261       }
  262   
  263       /**
  264        * Returns the detail message string of this throwable.
  265        *
  266        * @return  the detail message string of this <tt>Throwable</tt> instance
  267        *          (which may be <tt>null</tt>).
  268        */
  269       public String getMessage() {
  270           return detailMessage;
  271       }
  272   
  273       /**
  274        * Creates a localized description of this throwable.
  275        * Subclasses may override this method in order to produce a
  276        * locale-specific message.  For subclasses that do not override this
  277        * method, the default implementation returns the same result as
  278        * <code>getMessage()</code>.
  279        *
  280        * @return  The localized description of this throwable.
  281        * @since   JDK1.1
  282        */
  283       public String getLocalizedMessage() {
  284           return getMessage();
  285       }
  286   
  287       /**
  288        * Returns the cause of this throwable or <code>null</code> if the
  289        * cause is nonexistent or unknown.  (The cause is the throwable that
  290        * caused this throwable to get thrown.)
  291        *
  292        * <p>This implementation returns the cause that was supplied via one of
  293        * the constructors requiring a <tt>Throwable</tt>, or that was set after
  294        * creation with the {@link #initCause(Throwable)} method.  While it is
  295        * typically unnecessary to override this method, a subclass can override
  296        * it to return a cause set by some other means.  This is appropriate for
  297        * a "legacy chained throwable" that predates the addition of chained
  298        * exceptions to <tt>Throwable</tt>.  Note that it is <i>not</i>
  299        * necessary to override any of the <tt>PrintStackTrace</tt> methods,
  300        * all of which invoke the <tt>getCause</tt> method to determine the
  301        * cause of a throwable.
  302        *
  303        * @return  the cause of this throwable or <code>null</code> if the
  304        *          cause is nonexistent or unknown.
  305        * @since 1.4
  306        */
  307       public Throwable getCause() {
  308           return (cause==this ? null : cause);
  309       }
  310   
  311       /**
  312        * Initializes the <i>cause</i> of this throwable to the specified value.
  313        * (The cause is the throwable that caused this throwable to get thrown.)
  314        *
  315        * <p>This method can be called at most once.  It is generally called from
  316        * within the constructor, or immediately after creating the
  317        * throwable.  If this throwable was created
  318        * with {@link #Throwable(Throwable)} or
  319        * {@link #Throwable(String,Throwable)}, this method cannot be called
  320        * even once.
  321        *
  322        * @param  cause the cause (which is saved for later retrieval by the
  323        *         {@link #getCause()} method).  (A <tt>null</tt> value is
  324        *         permitted, and indicates that the cause is nonexistent or
  325        *         unknown.)
  326        * @return  a reference to this <code>Throwable</code> instance.
  327        * @throws IllegalArgumentException if <code>cause</code> is this
  328        *         throwable.  (A throwable cannot be its own cause.)
  329        * @throws IllegalStateException if this throwable was
  330        *         created with {@link #Throwable(Throwable)} or
  331        *         {@link #Throwable(String,Throwable)}, or this method has already
  332        *         been called on this throwable.
  333        * @since  1.4
  334        */
  335       public synchronized Throwable initCause(Throwable cause) {
  336           if (this.cause != this)
  337               throw new IllegalStateException("Can't overwrite cause");
  338           if (cause == this)
  339               throw new IllegalArgumentException("Self-causation not permitted");
  340           this.cause = cause;
  341           return this;
  342       }
  343   
  344       /**
  345        * Returns a short description of this throwable.
  346        * The result is the concatenation of:
  347        * <ul>
  348        * <li> the {@linkplain Class#getName() name} of the class of this object
  349        * <li> ": " (a colon and a space)
  350        * <li> the result of invoking this object's {@link #getLocalizedMessage}
  351        *      method
  352        * </ul>
  353        * If <tt>getLocalizedMessage</tt> returns <tt>null</tt>, then just
  354        * the class name is returned.
  355        *
  356        * @return a string representation of this throwable.
  357        */
  358       public String toString() {
  359           String s = getClass().getName();
  360           String message = getLocalizedMessage();
  361           return (message != null) ? (s + ": " + message) : s;
  362       }
  363   
  364       /**
  365        * Prints this throwable and its backtrace to the
  366        * standard error stream. This method prints a stack trace for this
  367        * <code>Throwable</code> object on the error output stream that is
  368        * the value of the field <code>System.err</code>. The first line of
  369        * output contains the result of the {@link #toString()} method for
  370        * this object.  Remaining lines represent data previously recorded by
  371        * the method {@link #fillInStackTrace()}. The format of this
  372        * information depends on the implementation, but the following
  373        * example may be regarded as typical:
  374        * <blockquote><pre>
  375        * java.lang.NullPointerException
  376        *         at MyClass.mash(MyClass.java:9)
  377        *         at MyClass.crunch(MyClass.java:6)
  378        *         at MyClass.main(MyClass.java:3)
  379        * </pre></blockquote>
  380        * This example was produced by running the program:
  381        * <pre>
  382        * class MyClass {
  383        *     public static void main(String[] args) {
  384        *         crunch(null);
  385        *     }
  386        *     static void crunch(int[] a) {
  387        *         mash(a);
  388        *     }
  389        *     static void mash(int[] b) {
  390        *         System.out.println(b[0]);
  391        *     }
  392        * }
  393        * </pre>
  394        * The backtrace for a throwable with an initialized, non-null cause
  395        * should generally include the backtrace for the cause.  The format
  396        * of this information depends on the implementation, but the following
  397        * example may be regarded as typical:
  398        * <pre>
  399        * HighLevelException: MidLevelException: LowLevelException
  400        *         at Junk.a(Junk.java:13)
  401        *         at Junk.main(Junk.java:4)
  402        * Caused by: MidLevelException: LowLevelException
  403        *         at Junk.c(Junk.java:23)
  404        *         at Junk.b(Junk.java:17)
  405        *         at Junk.a(Junk.java:11)
  406        *         ... 1 more
  407        * Caused by: LowLevelException
  408        *         at Junk.e(Junk.java:30)
  409        *         at Junk.d(Junk.java:27)
  410        *         at Junk.c(Junk.java:21)
  411        *         ... 3 more
  412        * </pre>
  413        * Note the presence of lines containing the characters <tt>"..."</tt>.
  414        * These lines indicate that the remainder of the stack trace for this
  415        * exception matches the indicated number of frames from the bottom of the
  416        * stack trace of the exception that was caused by this exception (the
  417        * "enclosing" exception).  This shorthand can greatly reduce the length
  418        * of the output in the common case where a wrapped exception is thrown
  419        * from same method as the "causative exception" is caught.  The above
  420        * example was produced by running the program:
  421        * <pre>
  422        * public class Junk {
  423        *     public static void main(String args[]) {
  424        *         try {
  425        *             a();
  426        *         } catch(HighLevelException e) {
  427        *             e.printStackTrace();
  428        *         }
  429        *     }
  430        *     static void a() throws HighLevelException {
  431        *         try {
  432        *             b();
  433        *         } catch(MidLevelException e) {
  434        *             throw new HighLevelException(e);
  435        *         }
  436        *     }
  437        *     static void b() throws MidLevelException {
  438        *         c();
  439        *     }
  440        *     static void c() throws MidLevelException {
  441        *         try {
  442        *             d();
  443        *         } catch(LowLevelException e) {
  444        *             throw new MidLevelException(e);
  445        *         }
  446        *     }
  447        *     static void d() throws LowLevelException {
  448        *        e();
  449        *     }
  450        *     static void e() throws LowLevelException {
  451        *         throw new LowLevelException();
  452        *     }
  453        * }
  454        *
  455        * class HighLevelException extends Exception {
  456        *     HighLevelException(Throwable cause) { super(cause); }
  457        * }
  458        *
  459        * class MidLevelException extends Exception {
  460        *     MidLevelException(Throwable cause)  { super(cause); }
  461        * }
  462        *
  463        * class LowLevelException extends Exception {
  464        * }
  465        * </pre>
  466        */
  467       public void printStackTrace() {
  468           printStackTrace(System.err);
  469       }
  470   
  471       /**
  472        * Prints this throwable and its backtrace to the specified print stream.
  473        *
  474        * @param s <code>PrintStream</code> to use for output
  475        */
  476       public void printStackTrace(PrintStream s) {
  477           synchronized (s) {
  478               s.println(this);
  479               StackTraceElement[] trace = getOurStackTrace();
  480               for (int i=0; i < trace.length; i++)
  481                   s.println("\tat " + trace[i]);
  482   
  483               Throwable ourCause = getCause();
  484               if (ourCause != null)
  485                   ourCause.printStackTraceAsCause(s, trace);
  486           }
  487       }
  488   
  489       /**
  490        * Print our stack trace as a cause for the specified stack trace.
  491        */
  492       private void printStackTraceAsCause(PrintStream s,
  493                                           StackTraceElement[] causedTrace)
  494       {
  495           // assert Thread.holdsLock(s);
  496   
  497           // Compute number of frames in common between this and caused
  498           StackTraceElement[] trace = getOurStackTrace();
  499           int m = trace.length-1, n = causedTrace.length-1;
  500           while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) {
  501               m--; n--;
  502           }
  503           int framesInCommon = trace.length - 1 - m;
  504   
  505           s.println("Caused by: " + this);
  506           for (int i=0; i <= m; i++)
  507               s.println("\tat " + trace[i]);
  508           if (framesInCommon != 0)
  509               s.println("\t... " + framesInCommon + " more");
  510   
  511           // Recurse if we have a cause
  512           Throwable ourCause = getCause();
  513           if (ourCause != null)
  514               ourCause.printStackTraceAsCause(s, trace);
  515       }
  516   
  517       /**
  518        * Prints this throwable and its backtrace to the specified
  519        * print writer.
  520        *
  521        * @param s <code>PrintWriter</code> to use for output
  522        * @since   JDK1.1
  523        */
  524       public void printStackTrace(PrintWriter s) {
  525           synchronized (s) {
  526               s.println(this);
  527               StackTraceElement[] trace = getOurStackTrace();
  528               for (int i=0; i < trace.length; i++)
  529                   s.println("\tat " + trace[i]);
  530   
  531               Throwable ourCause = getCause();
  532               if (ourCause != null)
  533                   ourCause.printStackTraceAsCause(s, trace);
  534           }
  535       }
  536   
  537       /**
  538        * Print our stack trace as a cause for the specified stack trace.
  539        */
  540       private void printStackTraceAsCause(PrintWriter s,
  541                                           StackTraceElement[] causedTrace)
  542       {
  543           // assert Thread.holdsLock(s);
  544   
  545           // Compute number of frames in common between this and caused
  546           StackTraceElement[] trace = getOurStackTrace();
  547           int m = trace.length-1, n = causedTrace.length-1;
  548           while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) {
  549               m--; n--;
  550           }
  551           int framesInCommon = trace.length - 1 - m;
  552   
  553           s.println("Caused by: " + this);
  554           for (int i=0; i <= m; i++)
  555               s.println("\tat " + trace[i]);
  556           if (framesInCommon != 0)
  557               s.println("\t... " + framesInCommon + " more");
  558   
  559           // Recurse if we have a cause
  560           Throwable ourCause = getCause();
  561           if (ourCause != null)
  562               ourCause.printStackTraceAsCause(s, trace);
  563       }
  564   
  565       /**
  566        * Fills in the execution stack trace. This method records within this
  567        * <code>Throwable</code> object information about the current state of
  568        * the stack frames for the current thread.
  569        *
  570        * @return  a reference to this <code>Throwable</code> instance.
  571        * @see     java.lang.Throwable#printStackTrace()
  572        */
  573       public synchronized native Throwable fillInStackTrace();
  574   
  575       /**
  576        * Provides programmatic access to the stack trace information printed by
  577        * {@link #printStackTrace()}.  Returns an array of stack trace elements,
  578        * each representing one stack frame.  The zeroth element of the array
  579        * (assuming the array's length is non-zero) represents the top of the
  580        * stack, which is the last method invocation in the sequence.  Typically,
  581        * this is the point at which this throwable was created and thrown.
  582        * The last element of the array (assuming the array's length is non-zero)
  583        * represents the bottom of the stack, which is the first method invocation
  584        * in the sequence.
  585        *
  586        * <p>Some virtual machines may, under some circumstances, omit one
  587        * or more stack frames from the stack trace.  In the extreme case,
  588        * a virtual machine that has no stack trace information concerning
  589        * this throwable is permitted to return a zero-length array from this
  590        * method.  Generally speaking, the array returned by this method will
  591        * contain one element for every frame that would be printed by
  592        * <tt>printStackTrace</tt>.
  593        *
  594        * @return an array of stack trace elements representing the stack trace
  595        *         pertaining to this throwable.
  596        * @since  1.4
  597        */
  598       public StackTraceElement[] getStackTrace() {
  599           return getOurStackTrace().clone();
  600       }
  601   
  602       private synchronized StackTraceElement[] getOurStackTrace() {
  603           // Initialize stack trace if this is the first call to this method
  604           if (stackTrace == null) {
  605               int depth = getStackTraceDepth();
  606               stackTrace = new StackTraceElement[depth];
  607               for (int i=0; i < depth; i++)
  608                   stackTrace[i] = getStackTraceElement(i);
  609           }
  610           return stackTrace;
  611       }
  612   
  613       /**
  614        * Sets the stack trace elements that will be returned by
  615        * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
  616        * and related methods.
  617        *
  618        * This method, which is designed for use by RPC frameworks and other
  619        * advanced systems, allows the client to override the default
  620        * stack trace that is either generated by {@link #fillInStackTrace()}
  621        * when a throwable is constructed or deserialized when a throwable is
  622        * read from a serialization stream.
  623        *
  624        * @param   stackTrace the stack trace elements to be associated with
  625        * this <code>Throwable</code>.  The specified array is copied by this
  626        * call; changes in the specified array after the method invocation
  627        * returns will have no affect on this <code>Throwable</code>'s stack
  628        * trace.
  629        *
  630        * @throws NullPointerException if <code>stackTrace</code> is
  631        *         <code>null</code>, or if any of the elements of
  632        *         <code>stackTrace</code> are <code>null</code>
  633        *
  634        * @since  1.4
  635        */
  636       public void setStackTrace(StackTraceElement[] stackTrace) {
  637           StackTraceElement[] defensiveCopy = stackTrace.clone();
  638           for (int i = 0; i < defensiveCopy.length; i++)
  639               if (defensiveCopy[i] == null)
  640                   throw new NullPointerException("stackTrace[" + i + "]");
  641   
  642           this.stackTrace = defensiveCopy;
  643       }
  644   
  645       /**
  646        * Returns the number of elements in the stack trace (or 0 if the stack
  647        * trace is unavailable).
  648        */
  649       private native int getStackTraceDepth();
  650   
  651       /**
  652        * Returns the specified element of the stack trace.
  653        *
  654        * @param index index of the element to return.
  655        * @throws IndexOutOfBoundsException if <tt>index &lt; 0 ||
  656        *         index &gt;= getStackTraceDepth() </tt>
  657        */
  658       private native StackTraceElement getStackTraceElement(int index);
  659   
  660       private synchronized void writeObject(java.io.ObjectOutputStream s)
  661           throws IOException
  662       {
  663           getOurStackTrace();  // Ensure that stackTrace field is initialized.
  664           s.defaultWriteObject();
  665       }
  666   }

Save This Page
Home » openjdk-7 » java » lang » [javadoc | source]