Merge from the pain train
[official-gcc.git] / libjava / java / lang / Throwable.java
blobad5157823f5b53f488e133298a5b037426c6787e
1 /* java.lang.Throwable -- Root class for all Exceptions and Errors
2 Copyright (C) 1998, 1999, 2002, 2004, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 package java.lang;
40 import java.io.PrintStream;
41 import java.io.PrintWriter;
42 import java.io.Serializable;
44 /**
45 * Throwable is the superclass of all exceptions that can be raised.
47 * <p>There are two special cases: {@link Error} and {@link RuntimeException}:
48 * these two classes (and their subclasses) are considered unchecked
49 * exceptions, and are either frequent enough or catastrophic enough that you
50 * do not need to declare them in <code>throws</code> clauses. Everything
51 * else is a checked exception, and is ususally a subclass of
52 * {@link Exception}; these exceptions have to be handled or declared.
54 * <p>Instances of this class are usually created with knowledge of the
55 * execution context, so that you can get a stack trace of the problem spot
56 * in the code. Also, since JDK 1.4, Throwables participate in "exception
57 * chaining." This means that one exception can be caused by another, and
58 * preserve the information of the original.
60 * <p>One reason this is useful is to wrap exceptions to conform to an
61 * interface. For example, it would be bad design to require all levels
62 * of a program interface to be aware of the low-level exceptions thrown
63 * at one level of abstraction. Another example is wrapping a checked
64 * exception in an unchecked one, to communicate that failure occured
65 * while still obeying the method throws clause of a superclass.
67 * <p>A cause is assigned in one of two ways; but can only be assigned once
68 * in the lifetime of the Throwable. There are new constructors added to
69 * several classes in the exception hierarchy that directly initialize the
70 * cause, or you can use the <code>initCause</code> method. This second
71 * method is especially useful if the superclass has not been retrofitted
72 * with new constructors:<br>
73 * <pre>
74 * try
75 * {
76 * lowLevelOp();
77 * }
78 * catch (LowLevelException lle)
79 * {
80 * throw (HighLevelException) new HighLevelException().initCause(lle);
81 * }
82 * </pre>
83 * Notice the cast in the above example; without it, your method would need
84 * a throws clase that declared Throwable, defeating the purpose of chainig
85 * your exceptions.
87 * <p>By convention, exception classes have two constructors: one with no
88 * arguments, and one that takes a String for a detail message. Further,
89 * classes which are likely to be used in an exception chain also provide
90 * a constructor that takes a Throwable, with or without a detail message
91 * string.
93 * <p>Another 1.4 feature is the StackTrace, a means of reflection that
94 * allows the program to inspect the context of the exception, and which is
95 * serialized, so that remote procedure calls can correctly pass exceptions.
97 * @author Brian Jones
98 * @author John Keiser
99 * @author Mark Wielaard
100 * @author Tom Tromey
101 * @author Eric Blake (ebb9@email.byu.edu)
102 * @since 1.0
103 * @status updated to 1.4
105 public class Throwable implements Serializable
108 * Compatible with JDK 1.0+.
110 private static final long serialVersionUID = -3042686055658047285L;
113 * The detail message.
115 * @serial specific details about the exception, may be null
117 private final String detailMessage;
120 * The cause of the throwable, including null for an unknown or non-chained
121 * cause. This may only be set once; so the field is set to
122 * <code>this</code> until initialized.
124 * @serial the cause, or null if unknown, or this if not yet set
125 * @since 1.4
127 private Throwable cause = this;
130 * The stack trace, in a serialized form.
132 * @serial the elements of the stack trace; this is non-null, and has
133 * no null entries
134 * @since 1.4
136 private StackTraceElement[] stackTrace;
139 * Instantiate this Throwable with an empty message. The cause remains
140 * uninitialized. {@link #fillInStackTrace()} will be called to set
141 * up the stack trace.
143 public Throwable()
145 this((String) null);
149 * Instantiate this Throwable with the given message. The cause remains
150 * uninitialized. {@link #fillInStackTrace()} will be called to set
151 * up the stack trace.
153 * @param message the message to associate with the Throwable
155 public Throwable(String message)
157 fillInStackTrace();
158 detailMessage = message;
162 * Instantiate this Throwable with the given message and cause. Note that
163 * the message is unrelated to the message of the cause.
164 * {@link #fillInStackTrace()} will be called to set up the stack trace.
166 * @param message the message to associate with the Throwable
167 * @param cause the cause, may be null
168 * @since 1.4
170 public Throwable(String message, Throwable cause)
172 this(message);
173 initCause(cause);
177 * Instantiate this Throwable with the given cause. The message is then
178 * built as <code>cause == null ? null : cause.toString()</code>.
179 * {@link #fillInStackTrace()} will be called to set up the stack trace.
181 * @param cause the cause, may be null
182 * @since 1.4
184 public Throwable(Throwable cause)
186 this(cause == null ? null : cause.toString(), cause);
190 * Get the message associated with this Throwable.
192 * @return the error message associated with this Throwable, may be null
194 public String getMessage()
196 return detailMessage;
200 * Get a localized version of this Throwable's error message.
201 * This method must be overridden in a subclass of Throwable
202 * to actually produce locale-specific methods. The Throwable
203 * implementation just returns getMessage().
205 * @return a localized version of this error message
206 * @see #getMessage()
207 * @since 1.1
209 public String getLocalizedMessage()
211 return getMessage();
215 * Returns the cause of this exception, or null if the cause is not known
216 * or non-existant. This cause is initialized by the new constructors,
217 * or by calling initCause.
219 * @return the cause of this Throwable
220 * @since 1.4
222 public Throwable getCause()
224 return cause == this ? null : cause;
228 * Initialize the cause of this Throwable. This may only be called once
229 * during the object lifetime, including implicitly by chaining
230 * constructors.
232 * @param cause the cause of this Throwable, may be null
233 * @return this
234 * @throws IllegalArgumentException if cause is this (a Throwable can't be
235 * its own cause!)
236 * @throws IllegalStateException if the cause has already been set
237 * @since 1.4
239 public Throwable initCause(Throwable cause)
241 if (cause == this)
242 throw new IllegalArgumentException();
243 if (this.cause != this)
244 throw new IllegalStateException();
245 this.cause = cause;
246 return this;
250 * Get a human-readable representation of this Throwable. The detail message
251 * is retrieved by getLocalizedMessage(). Then, with a null detail
252 * message, this string is simply the object's class name; otherwise
253 * the string is <code>getClass().getName() + ": " + message</code>.
255 * @return a human-readable String represting this Throwable
257 public String toString()
259 String msg = getLocalizedMessage();
260 return getClass().getName() + (msg == null ? "" : ": " + msg);
264 * Print a stack trace to the standard error stream. This stream is the
265 * current contents of <code>System.err</code>. The first line of output
266 * is the result of {@link #toString()}, and the remaining lines represent
267 * the data created by {@link #fillInStackTrace()}. While the format is
268 * unspecified, this implementation uses the suggested format, demonstrated
269 * by this example:<br>
270 * <pre>
271 * public class Junk
273 * public static void main(String args[])
275 * try
277 * a();
279 * catch(HighLevelException e)
281 * e.printStackTrace();
284 * static void a() throws HighLevelException
286 * try
288 * b();
290 * catch(MidLevelException e)
292 * throw new HighLevelException(e);
295 * static void b() throws MidLevelException
297 * c();
299 * static void c() throws MidLevelException
301 * try
303 * d();
305 * catch(LowLevelException e)
307 * throw new MidLevelException(e);
310 * static void d() throws LowLevelException
312 * e();
314 * static void e() throws LowLevelException
316 * throw new LowLevelException();
319 * class HighLevelException extends Exception
321 * HighLevelException(Throwable cause) { super(cause); }
323 * class MidLevelException extends Exception
325 * MidLevelException(Throwable cause) { super(cause); }
327 * class LowLevelException extends Exception
330 * </pre>
331 * <p>
332 * <pre>
333 * HighLevelException: MidLevelException: LowLevelException
334 * at Junk.a(Junk.java:13)
335 * at Junk.main(Junk.java:4)
336 * Caused by: MidLevelException: LowLevelException
337 * at Junk.c(Junk.java:23)
338 * at Junk.b(Junk.java:17)
339 * at Junk.a(Junk.java:11)
340 * ... 1 more
341 * Caused by: LowLevelException
342 * at Junk.e(Junk.java:30)
343 * at Junk.d(Junk.java:27)
344 * at Junk.c(Junk.java:21)
345 * ... 3 more
346 * </pre>
348 public void printStackTrace()
350 printStackTrace(System.err);
354 * Print a stack trace to the specified PrintStream. See
355 * {@link #printStackTrace()} for the sample format.
357 * @param s the PrintStream to write the trace to
359 public void printStackTrace(PrintStream s)
361 s.print(stackTraceString());
365 * Prints the exception, the detailed message and the stack trace
366 * associated with this Throwable to the given <code>PrintWriter</code>.
367 * The actual output written is implemention specific. Use the result of
368 * <code>getStackTrace()</code> when more precise information is needed.
370 * <p>This implementation first prints a line with the result of this
371 * object's <code>toString()</code> method.
372 * <br>
373 * Then for all elements given by <code>getStackTrace</code> it prints
374 * a line containing three spaces, the string "at " and the result of calling
375 * the <code>toString()</code> method on the <code>StackTraceElement</code>
376 * object. If <code>getStackTrace()</code> returns an empty array it prints
377 * a line containing three spaces and the string
378 * "&lt;&lt;No stacktrace available&gt;&gt;".
379 * <br>
380 * Then if <code>getCause()</code> doesn't return null it adds a line
381 * starting with "Caused by: " and the result of calling
382 * <code>toString()</code> on the cause.
383 * <br>
384 * Then for every cause (of a cause, etc) the stacktrace is printed the
385 * same as for the top level <code>Throwable</code> except that as soon
386 * as all the remaining stack frames of the cause are the same as the
387 * the last stack frames of the throwable that the cause is wrapped in
388 * then a line starting with three spaces and the string "... X more" is
389 * printed, where X is the number of remaining stackframes.
391 * @param pw the PrintWriter to write the trace to
392 * @since 1.1
394 public void printStackTrace (PrintWriter pw)
396 pw.print(stackTraceString());
400 * We use inner class to avoid a static initializer in this basic class.
402 private static class StaticData
404 static final String nl;
406 static
408 // Access package private properties field to prevent Security check.
409 nl = System.properties.getProperty("line.separator");
413 // Create whole stack trace in a stringbuffer so we don't have to print
414 // it line by line. This prevents printing multiple stack traces from
415 // different threads to get mixed up when written to the same PrintWriter.
416 private String stackTraceString()
418 StringBuffer sb = new StringBuffer();
420 // Main stacktrace
421 StackTraceElement[] stack = getStackTrace();
422 stackTraceStringBuffer(sb, this.toString(), stack, 0);
424 // The cause(s)
425 Throwable cause = getCause();
426 while (cause != null)
428 // Cause start first line
429 sb.append("Caused by: ");
431 // Cause stacktrace
432 StackTraceElement[] parentStack = stack;
433 stack = cause.getStackTrace();
434 if (parentStack == null || parentStack.length == 0)
435 stackTraceStringBuffer(sb, cause.toString(), stack, 0);
436 else
438 int equal = 0; // Count how many of the last stack frames are equal
439 int frame = stack.length-1;
440 int parentFrame = parentStack.length-1;
441 while (frame > 0 && parentFrame > 0)
443 if (stack[frame].equals(parentStack[parentFrame]))
445 equal++;
446 frame--;
447 parentFrame--;
449 else
450 break;
452 stackTraceStringBuffer(sb, cause.toString(), stack, equal);
454 cause = cause.getCause();
457 return sb.toString();
460 // Adds to the given StringBuffer a line containing the name and
461 // all stacktrace elements minus the last equal ones.
462 private static void stackTraceStringBuffer(StringBuffer sb, String name,
463 StackTraceElement[] stack, int equal)
465 String nl = StaticData.nl;
466 // (finish) first line
467 sb.append(name);
468 sb.append(nl);
470 // The stacktrace
471 if (stack == null || stack.length == 0)
473 sb.append(" <<No stacktrace available>>");
474 sb.append(nl);
476 else
478 for (int i = 0; i < stack.length-equal; i++)
480 sb.append(" at ");
481 sb.append(stack[i] == null ? "<<Unknown>>" : stack[i].toString());
482 sb.append(nl);
484 if (equal > 0)
486 sb.append(" ...");
487 sb.append(equal);
488 sb.append(" more");
489 sb.append(nl);
495 * Fill in the stack trace with the current execution stack.
497 * @return this same throwable
498 * @see #printStackTrace()
500 public Throwable fillInStackTrace()
502 vmState = VMThrowable.fillInStackTrace(this);
503 stackTrace = null; // Should be regenerated when used.
505 return this;
509 * Provides access to the information printed in {@link #printStackTrace()}.
510 * The array is non-null, with no null entries, although the virtual
511 * machine is allowed to skip stack frames. If the array is not 0-length,
512 * then slot 0 holds the information on the stack frame where the Throwable
513 * was created (or at least where <code>fillInStackTrace()</code> was
514 * called).
516 * @return an array of stack trace information, as available from the VM
517 * @since 1.4
519 public StackTraceElement[] getStackTrace()
521 if (stackTrace == null)
522 if (vmState == null)
523 stackTrace = new StackTraceElement[0];
524 else
526 stackTrace = vmState.getStackTrace(this);
527 vmState = null; // No longer needed
530 return stackTrace;
534 * Change the stack trace manually. This method is designed for remote
535 * procedure calls, which intend to alter the stack trace before or after
536 * serialization according to the context of the remote call.
537 * <p>
538 * The contents of the given stacktrace is copied so changes to the
539 * original array do not change the stack trace elements of this
540 * throwable.
542 * @param stackTrace the new trace to use
543 * @throws NullPointerException if stackTrace is null or has null elements
544 * @since 1.4
546 public void setStackTrace(StackTraceElement[] stackTrace)
548 int i = stackTrace.length;
549 StackTraceElement[] st = new StackTraceElement[i];
551 while (--i >= 0)
553 st[i] = stackTrace[i];
554 if (st[i] == null)
555 throw new NullPointerException("Element " + i + " null");
558 this.stackTrace = st;
562 * VM state when fillInStackTrace was called.
563 * Used by getStackTrace() to get an array of StackTraceElements.
564 * Cleared when no longer needed.
566 private transient VMThrowable vmState;