01: //////////////////////////////////////////////////////////////////////////////
02: // Clirr: compares two versions of a java library for binary compatibility
03: // Copyright (C) 2003 - 2005 Lars Kühne
04: //
05: // This library is free software; you can redistribute it and/or
06: // modify it under the terms of the GNU Lesser General Public
07: // License as published by the Free Software Foundation; either
08: // version 2.1 of the License, or (at your option) any later version.
09: //
10: // This library is distributed in the hope that it will be useful,
11: // but WITHOUT ANY WARRANTY; without even the implied warranty of
12: // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: // Lesser General Public License for more details.
14: //
15: // You should have received a copy of the GNU Lesser General Public
16: // License along with this library; if not, write to the Free Software
17: // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: //////////////////////////////////////////////////////////////////////////////
19:
20: package net.sf.clirr.core.internal;
21:
22: import java.lang.reflect.Method;
23:
24: /**
25: * A helper class to initialize the cause of an exception.
26: *
27: * This allows Clirr to be compile time compatible with JDK 1.3
28: * at still taking advantage of the JDK 1.4 chained exceptions feature
29: * if available.
30: *
31: * @author lkuehne
32: */
33: public final class ExceptionUtil {
34: /** Disallow instantiation. */
35: private ExceptionUtil() {
36: }
37:
38: private static Method initCauseMethod;
39:
40: static {
41: try {
42: initCauseMethod = Throwable.class.getMethod("initCause",
43: new Class[] { Throwable.class });
44: } catch (NoSuchMethodException e) {
45: // we're on JDK < 1.4, no cause data will be available in Exception stacktraces
46: initCauseMethod = null;
47: }
48: }
49:
50: /**
51: * Initializes the chained exception if possible.
52: * Does nothing if chained exceptions are not available on the
53: * current JDK (1.3 or lower).
54: *
55: * @param t the resulting exception (high abstraction level)
56: * @param cause the underlying cause of t (low abstraction level)
57: */
58: public static void initCause(Throwable t, Throwable cause) {
59: if (initCauseMethod == null) {
60: return;
61: }
62:
63: try {
64: initCauseMethod.invoke(t, new Throwable[] { cause });
65: } catch (Exception e) {
66: if (e instanceof RuntimeException) {
67: throw (RuntimeException) e;
68: }
69: throw new RuntimeException("unable to initCause: "
70: + e.toString());
71: }
72: }
73: }
|