Throwable.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /* java.lang.Throwable -- Root class for all Exceptions and Errors
  2. Copyright (C) 1998, 1999, 2002, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.lang;
  32. import gnu.classpath.SystemProperties;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.io.PrintStream;
  35. import java.io.PrintWriter;
  36. import java.io.Serializable;
  37. /**
  38. * Throwable is the superclass of all exceptions that can be raised.
  39. *
  40. * <p>There are two special cases: {@link Error} and {@link RuntimeException}:
  41. * these two classes (and their subclasses) are considered unchecked
  42. * exceptions, and are either frequent enough or catastrophic enough that you
  43. * do not need to declare them in <code>throws</code> clauses. Everything
  44. * else is a checked exception, and is ususally a subclass of
  45. * {@link Exception}; these exceptions have to be handled or declared.
  46. *
  47. * <p>Instances of this class are usually created with knowledge of the
  48. * execution context, so that you can get a stack trace of the problem spot
  49. * in the code. Also, since JDK 1.4, Throwables participate in "exception
  50. * chaining." This means that one exception can be caused by another, and
  51. * preserve the information of the original.
  52. *
  53. * <p>One reason this is useful is to wrap exceptions to conform to an
  54. * interface. For example, it would be bad design to require all levels
  55. * of a program interface to be aware of the low-level exceptions thrown
  56. * at one level of abstraction. Another example is wrapping a checked
  57. * exception in an unchecked one, to communicate that failure occured
  58. * while still obeying the method throws clause of a superclass.
  59. *
  60. * <p>A cause is assigned in one of two ways; but can only be assigned once
  61. * in the lifetime of the Throwable. There are new constructors added to
  62. * several classes in the exception hierarchy that directly initialize the
  63. * cause, or you can use the <code>initCause</code> method. This second
  64. * method is especially useful if the superclass has not been retrofitted
  65. * with new constructors:<br>
  66. * <pre>
  67. * try
  68. * {
  69. * lowLevelOp();
  70. * }
  71. * catch (LowLevelException lle)
  72. * {
  73. * throw (HighLevelException) new HighLevelException().initCause(lle);
  74. * }
  75. * </pre>
  76. * Notice the cast in the above example; without it, your method would need
  77. * a throws clase that declared Throwable, defeating the purpose of chainig
  78. * your exceptions.
  79. *
  80. * <p>By convention, exception classes have two constructors: one with no
  81. * arguments, and one that takes a String for a detail message. Further,
  82. * classes which are likely to be used in an exception chain also provide
  83. * a constructor that takes a Throwable, with or without a detail message
  84. * string.
  85. *
  86. * <p>Another 1.4 feature is the StackTrace, a means of reflection that
  87. * allows the program to inspect the context of the exception, and which is
  88. * serialized, so that remote procedure calls can correctly pass exceptions.
  89. *
  90. * @author Brian Jones
  91. * @author John Keiser
  92. * @author Mark Wielaard
  93. * @author Tom Tromey
  94. * @author Eric Blake (ebb9@email.byu.edu)
  95. * @since 1.0
  96. * @status updated to 1.4
  97. */
  98. public class Throwable implements Serializable
  99. {
  100. /**
  101. * Compatible with JDK 1.0+.
  102. */
  103. private static final long serialVersionUID = -3042686055658047285L;
  104. /**
  105. * The detail message.
  106. *
  107. * @serial specific details about the exception, may be null
  108. */
  109. private final String detailMessage;
  110. /**
  111. * The cause of the throwable, including null for an unknown or non-chained
  112. * cause. This may only be set once; so the field is set to
  113. * <code>this</code> until initialized.
  114. *
  115. * @serial the cause, or null if unknown, or this if not yet set
  116. * @since 1.4
  117. */
  118. private Throwable cause = this;
  119. /**
  120. * The stack trace, in a serialized form.
  121. *
  122. * @serial the elements of the stack trace; this is non-null, and has
  123. * no null entries
  124. * @since 1.4
  125. */
  126. private StackTraceElement[] stackTrace;
  127. /**
  128. * Instantiate this Throwable with an empty message. The cause remains
  129. * uninitialized. {@link #fillInStackTrace()} will be called to set
  130. * up the stack trace.
  131. */
  132. public Throwable()
  133. {
  134. this((String) null);
  135. }
  136. /**
  137. * Instantiate this Throwable with the given message. The cause remains
  138. * uninitialized. {@link #fillInStackTrace()} will be called to set
  139. * up the stack trace.
  140. *
  141. * @param message the message to associate with the Throwable
  142. */
  143. public Throwable(String message)
  144. {
  145. fillInStackTrace();
  146. detailMessage = message;
  147. }
  148. /**
  149. * Instantiate this Throwable with the given message and cause. Note that
  150. * the message is unrelated to the message of the cause.
  151. * {@link #fillInStackTrace()} will be called to set up the stack trace.
  152. *
  153. * @param message the message to associate with the Throwable
  154. * @param cause the cause, may be null
  155. * @since 1.4
  156. */
  157. public Throwable(String message, Throwable cause)
  158. {
  159. this(message);
  160. this.cause = cause;
  161. }
  162. /**
  163. * Instantiate this Throwable with the given cause. The message is then
  164. * built as <code>cause == null ? null : cause.toString()</code>.
  165. * {@link #fillInStackTrace()} will be called to set up the stack trace.
  166. *
  167. * @param cause the cause, may be null
  168. * @since 1.4
  169. */
  170. public Throwable(Throwable cause)
  171. {
  172. this(cause == null ? null : cause.toString(), cause);
  173. }
  174. /**
  175. * Get the message associated with this Throwable.
  176. *
  177. * @return the error message associated with this Throwable, may be null
  178. */
  179. public String getMessage()
  180. {
  181. return detailMessage;
  182. }
  183. /**
  184. * Get a localized version of this Throwable's error message.
  185. * This method must be overridden in a subclass of Throwable
  186. * to actually produce locale-specific methods. The Throwable
  187. * implementation just returns getMessage().
  188. *
  189. * @return a localized version of this error message
  190. * @see #getMessage()
  191. * @since 1.1
  192. */
  193. public String getLocalizedMessage()
  194. {
  195. return getMessage();
  196. }
  197. /**
  198. * Returns the cause of this exception, or null if the cause is not known
  199. * or non-existant. This cause is initialized by the new constructors,
  200. * or by calling initCause.
  201. *
  202. * @return the cause of this Throwable
  203. * @since 1.4
  204. */
  205. public Throwable getCause()
  206. {
  207. return cause == this ? null : cause;
  208. }
  209. /**
  210. * Initialize the cause of this Throwable. This may only be called once
  211. * during the object lifetime, including implicitly by chaining
  212. * constructors.
  213. *
  214. * @param cause the cause of this Throwable, may be null
  215. * @return this
  216. * @throws IllegalArgumentException if cause is this (a Throwable can't be
  217. * its own cause!)
  218. * @throws IllegalStateException if the cause has already been set
  219. * @since 1.4
  220. */
  221. public Throwable initCause(Throwable cause)
  222. {
  223. if (cause == this)
  224. throw new IllegalArgumentException();
  225. if (this.cause != this)
  226. throw new IllegalStateException();
  227. this.cause = cause;
  228. return this;
  229. }
  230. /**
  231. * Get a human-readable representation of this Throwable. The detail message
  232. * is retrieved by getLocalizedMessage(). Then, with a null detail
  233. * message, this string is simply the object's class name; otherwise
  234. * the string is <code>getClass().getName() + ": " + message</code>.
  235. *
  236. * @return a human-readable String represting this Throwable
  237. */
  238. public String toString()
  239. {
  240. String msg = getLocalizedMessage();
  241. return getClass().getName() + (msg == null ? "" : ": " + msg);
  242. }
  243. /**
  244. * Print a stack trace to the standard error stream. This stream is the
  245. * current contents of <code>System.err</code>. The first line of output
  246. * is the result of {@link #toString()}, and the remaining lines represent
  247. * the data created by {@link #fillInStackTrace()}. While the format is
  248. * unspecified, this implementation uses the suggested format, demonstrated
  249. * by this example:<br>
  250. * <pre>
  251. * public class Junk
  252. * {
  253. * public static void main(String args[])
  254. * {
  255. * try
  256. * {
  257. * a();
  258. * }
  259. * catch(HighLevelException e)
  260. * {
  261. * e.printStackTrace();
  262. * }
  263. * }
  264. * static void a() throws HighLevelException
  265. * {
  266. * try
  267. * {
  268. * b();
  269. * }
  270. * catch(MidLevelException e)
  271. * {
  272. * throw new HighLevelException(e);
  273. * }
  274. * }
  275. * static void b() throws MidLevelException
  276. * {
  277. * c();
  278. * }
  279. * static void c() throws MidLevelException
  280. * {
  281. * try
  282. * {
  283. * d();
  284. * }
  285. * catch(LowLevelException e)
  286. * {
  287. * throw new MidLevelException(e);
  288. * }
  289. * }
  290. * static void d() throws LowLevelException
  291. * {
  292. * e();
  293. * }
  294. * static void e() throws LowLevelException
  295. * {
  296. * throw new LowLevelException();
  297. * }
  298. * }
  299. * class HighLevelException extends Exception
  300. * {
  301. * HighLevelException(Throwable cause) { super(cause); }
  302. * }
  303. * class MidLevelException extends Exception
  304. * {
  305. * MidLevelException(Throwable cause) { super(cause); }
  306. * }
  307. * class LowLevelException extends Exception
  308. * {
  309. * }
  310. * </pre>
  311. * <p>
  312. * <pre>
  313. * HighLevelException: MidLevelException: LowLevelException
  314. * at Junk.a(Junk.java:13)
  315. * at Junk.main(Junk.java:4)
  316. * Caused by: MidLevelException: LowLevelException
  317. * at Junk.c(Junk.java:23)
  318. * at Junk.b(Junk.java:17)
  319. * at Junk.a(Junk.java:11)
  320. * ... 1 more
  321. * Caused by: LowLevelException
  322. * at Junk.e(Junk.java:30)
  323. * at Junk.d(Junk.java:27)
  324. * at Junk.c(Junk.java:21)
  325. * ... 3 more
  326. * </pre>
  327. */
  328. public void printStackTrace()
  329. {
  330. printStackTrace(System.err);
  331. }
  332. /**
  333. * Print a stack trace to the specified PrintStream. See
  334. * {@link #printStackTrace()} for the sample format.
  335. *
  336. * @param s the PrintStream to write the trace to
  337. */
  338. public void printStackTrace(PrintStream s)
  339. {
  340. s.print(stackTraceString());
  341. }
  342. /**
  343. * Prints the exception, the detailed message and the stack trace
  344. * associated with this Throwable to the given <code>PrintWriter</code>.
  345. * The actual output written is implemention specific. Use the result of
  346. * <code>getStackTrace()</code> when more precise information is needed.
  347. *
  348. * <p>This implementation first prints a line with the result of this
  349. * object's <code>toString()</code> method.
  350. * <br>
  351. * Then for all elements given by <code>getStackTrace</code> it prints
  352. * a line containing three spaces, the string "at " and the result of calling
  353. * the <code>toString()</code> method on the <code>StackTraceElement</code>
  354. * object. If <code>getStackTrace()</code> returns an empty array it prints
  355. * a line containing three spaces and the string
  356. * "&lt;&lt;No stacktrace available&gt;&gt;".
  357. * <br>
  358. * Then if <code>getCause()</code> doesn't return null it adds a line
  359. * starting with "Caused by: " and the result of calling
  360. * <code>toString()</code> on the cause.
  361. * <br>
  362. * Then for every cause (of a cause, etc) the stacktrace is printed the
  363. * same as for the top level <code>Throwable</code> except that as soon
  364. * as all the remaining stack frames of the cause are the same as the
  365. * the last stack frames of the throwable that the cause is wrapped in
  366. * then a line starting with three spaces and the string "... X more" is
  367. * printed, where X is the number of remaining stackframes.
  368. *
  369. * @param pw the PrintWriter to write the trace to
  370. * @since 1.1
  371. */
  372. public void printStackTrace (PrintWriter pw)
  373. {
  374. pw.print(stackTraceString());
  375. }
  376. /*
  377. * We use inner class to avoid a static initializer in this basic class.
  378. */
  379. private static class StaticData
  380. {
  381. static final String nl = SystemProperties.getProperty("line.separator");
  382. }
  383. // Create whole stack trace in a stringbuffer so we don't have to print
  384. // it line by line. This prevents printing multiple stack traces from
  385. // different threads to get mixed up when written to the same PrintWriter.
  386. private String stackTraceString()
  387. {
  388. CPStringBuilder sb = new CPStringBuilder();
  389. // Main stacktrace
  390. StackTraceElement[] stack = getStackTrace();
  391. stackTraceStringBuffer(sb, this.toString(), stack, 0);
  392. // The cause(s)
  393. Throwable cause = getCause();
  394. while (cause != null)
  395. {
  396. // Cause start first line
  397. sb.append("Caused by: ");
  398. // Cause stacktrace
  399. StackTraceElement[] parentStack = stack;
  400. stack = cause.getStackTrace();
  401. if (parentStack == null || parentStack.length == 0)
  402. stackTraceStringBuffer(sb, cause.toString(), stack, 0);
  403. else
  404. {
  405. int equal = 0; // Count how many of the last stack frames are equal
  406. int frame = stack.length-1;
  407. int parentFrame = parentStack.length-1;
  408. while (frame > 0 && parentFrame > 0)
  409. {
  410. if (stack[frame].equals(parentStack[parentFrame]))
  411. {
  412. equal++;
  413. frame--;
  414. parentFrame--;
  415. }
  416. else
  417. break;
  418. }
  419. stackTraceStringBuffer(sb, cause.toString(), stack, equal);
  420. }
  421. cause = cause.getCause();
  422. }
  423. return sb.toString();
  424. }
  425. // Adds to the given StringBuffer a line containing the name and
  426. // all stacktrace elements minus the last equal ones.
  427. private static void stackTraceStringBuffer(CPStringBuilder sb, String name,
  428. StackTraceElement[] stack, int equal)
  429. {
  430. String nl = StaticData.nl;
  431. // (finish) first line
  432. sb.append(name);
  433. sb.append(nl);
  434. // The stacktrace
  435. if (stack == null || stack.length == 0)
  436. {
  437. sb.append(" <<No stacktrace available>>");
  438. sb.append(nl);
  439. }
  440. else
  441. {
  442. for (int i = 0; i < stack.length-equal; i++)
  443. {
  444. sb.append(" at ");
  445. sb.append(stack[i] == null ? "<<Unknown>>" : stack[i].toString());
  446. sb.append(nl);
  447. }
  448. if (equal > 0)
  449. {
  450. sb.append(" ...");
  451. sb.append(equal);
  452. sb.append(" more");
  453. sb.append(nl);
  454. }
  455. }
  456. }
  457. /**
  458. * Fill in the stack trace with the current execution stack.
  459. *
  460. * @return this same throwable
  461. * @see #printStackTrace()
  462. */
  463. public Throwable fillInStackTrace()
  464. {
  465. vmState = VMThrowable.fillInStackTrace(this);
  466. stackTrace = null; // Should be regenerated when used.
  467. return this;
  468. }
  469. /**
  470. * Provides access to the information printed in {@link #printStackTrace()}.
  471. * The array is non-null, with no null entries, although the virtual
  472. * machine is allowed to skip stack frames. If the array is not 0-length,
  473. * then slot 0 holds the information on the stack frame where the Throwable
  474. * was created (or at least where <code>fillInStackTrace()</code> was
  475. * called).
  476. *
  477. * @return an array of stack trace information, as available from the VM
  478. * @since 1.4
  479. */
  480. public StackTraceElement[] getStackTrace()
  481. {
  482. if (stackTrace == null)
  483. if (vmState == null)
  484. stackTrace = new StackTraceElement[0];
  485. else
  486. {
  487. stackTrace = vmState.getStackTrace(this);
  488. vmState = null; // No longer needed
  489. }
  490. return stackTrace;
  491. }
  492. /**
  493. * Change the stack trace manually. This method is designed for remote
  494. * procedure calls, which intend to alter the stack trace before or after
  495. * serialization according to the context of the remote call.
  496. * <p>
  497. * The contents of the given stacktrace is copied so changes to the
  498. * original array do not change the stack trace elements of this
  499. * throwable.
  500. *
  501. * @param stackTrace the new trace to use
  502. * @throws NullPointerException if stackTrace is null or has null elements
  503. * @since 1.4
  504. */
  505. public void setStackTrace(StackTraceElement[] stackTrace)
  506. {
  507. int i = stackTrace.length;
  508. StackTraceElement[] st = new StackTraceElement[i];
  509. while (--i >= 0)
  510. {
  511. st[i] = stackTrace[i];
  512. if (st[i] == null)
  513. throw new NullPointerException("Element " + i + " null");
  514. }
  515. this.stackTrace = st;
  516. }
  517. /**
  518. * VM state when fillInStackTrace was called.
  519. * Used by getStackTrace() to get an array of StackTraceElements.
  520. * Cleared when no longer needed.
  521. */
  522. private transient VMThrowable vmState;
  523. }