01: // Copyright (c) 1999, 2003, 2005 Per M.A. Bothner.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.mapping;
05:
06: /** Encapsulate some Exception inside a RuntimeException.
07: * Inspired by org.xml.sax.SAXException written by David Megginson.
08: */
09:
10: public class WrappedException extends RuntimeException {
11: /**
12: * Create a new WrappedException.
13: */
14: public WrappedException() {
15: }
16:
17: /**
18: * Create a new WrappedException.
19: *
20: * @param message The error or warning message.
21: */
22: public WrappedException(String message) {
23: super (message);
24: }
25:
26: /**
27: * Create a new WrappedException wrapping an existing exception.
28: *
29: * <p>The existing exception will be embedded in the new
30: * one, and its message will become the default message for
31: * the WrappedException.</p>
32: *
33: * @param e The exception to be wrapped in a WrappedException.
34: */
35: public WrappedException(Throwable e) {
36: this (e.toString(), e);
37: }
38:
39: /**
40: * Create a new WrappedException from an existing exception.
41: *
42: * <p>The existing exception will be embedded in the new
43: * one, but the new exception will have its own message.</p>
44: *
45: * @param message The detail message.
46: * @param e The exception to be wrapped in a WrappedException.
47: */
48: public WrappedException(String message, Throwable e) {
49: /* #ifdef use:java.lang.Throwable.getCause */
50: super (message, e);
51: /* #else */
52: // super(message);
53: // initCause(e);
54: /* #endif */
55: }
56:
57: /**
58: * Return the embedded exception, if any.
59: *
60: * @return The embedded exception, or null if there is none.
61: */
62: public Throwable getException() {
63: return getCause();
64: }
65:
66: /**
67: * Convert this exception to a string.
68: *
69: * @return A string version of this exception.
70: */
71: public String toString() {
72: return getMessage();
73: }
74:
75: // The initCause/getCause functionality was added in JDK 1.4.
76: /* #ifndef use:java.lang.Throwable.getCause */
77: // public Throwable initCause(Throwable cause)
78: // {
79: // exception = cause;
80: // return this;
81: // }
82: // public Throwable getCause()
83: // {
84: // return exception;
85: // }
86: // private Throwable exception;
87: /* #endif */
88:
89: /** Coerce argument to a RuntimeException. */
90: public static RuntimeException wrapIfNeeded(Throwable ex) {
91: if (ex instanceof RuntimeException)
92: return (RuntimeException) ex;
93: else
94: return new WrappedException(ex);
95: }
96: }
|