01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2000,2008 Oracle. All rights reserved.
05: *
06: * $Id: ExceptionUnwrapper.java,v 1.16.2.2 2008/01/07 15:14:21 cwl Exp $
07: */
08:
09: package com.sleepycat.util;
10:
11: /**
12: * Unwraps nested exceptions by calling the {@link
13: * ExceptionWrapper#getCause()} method for exceptions that implement the
14: * {@link ExceptionWrapper} interface. Does not currently support the Java 1.4
15: * <code>Throwable.getCause()</code> method.
16: *
17: * @author Mark Hayes
18: */
19: public class ExceptionUnwrapper {
20:
21: /**
22: * Unwraps an Exception and returns the underlying Exception, or throws an
23: * Error if the underlying Throwable is an Error.
24: *
25: * @param e is the Exception to unwrap.
26: *
27: * @return the underlying Exception.
28: *
29: * @throws Error if the underlying Throwable is an Error.
30: *
31: * @throws IllegalArgumentException if the underlying Throwable is not an
32: * Exception or an Error.
33: */
34: public static Exception unwrap(Exception e) {
35:
36: Throwable t = unwrapAny(e);
37: if (t instanceof Exception) {
38: return (Exception) t;
39: } else if (t instanceof Error) {
40: throw (Error) t;
41: } else {
42: throw new IllegalArgumentException(
43: "Not Exception or Error: " + t);
44: }
45: }
46:
47: /**
48: * Unwraps an Exception and returns the underlying Throwable.
49: *
50: * @param e is the Exception to unwrap.
51: *
52: * @return the underlying Throwable.
53: */
54: public static Throwable unwrapAny(Throwable e) {
55:
56: while (true) {
57: if (e instanceof ExceptionWrapper) {
58: Throwable e2 = ((ExceptionWrapper) e).getCause();
59: if (e2 == null) {
60: return e;
61: } else {
62: e = e2;
63: }
64: } else {
65: return e;
66: }
67: }
68: }
69: }
|