Imported Upstream version 5.3.21
[platform/upstream/libdb.git] / lang / java / src / com / sleepycat / util / ExceptionUnwrapper.java
1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2000, 2012 Oracle and/or its affiliates.  All rights reserved.
5  *
6  */
7
8 package com.sleepycat.util;
9
10 /**
11  * Unwraps nested exceptions by calling the {@link
12  * ExceptionWrapper#getCause()} method for exceptions that implement the
13  * {@link ExceptionWrapper} interface.  Does not currently support the Java 1.4
14  * <code>Throwable.getCause()</code> method.
15  *
16  * @author Mark Hayes
17  */
18 public class ExceptionUnwrapper {
19
20     /**
21      * Unwraps an Exception and returns the underlying Exception, or throws an
22      * Error if the underlying Throwable is an Error.
23      *
24      * @param e is the Exception to unwrap.
25      *
26      * @return the underlying Exception.
27      *
28      * @throws Error if the underlying Throwable is an Error.
29      *
30      * @throws IllegalArgumentException if the underlying Throwable is not an
31      * Exception or an Error.
32      */
33     public static Exception unwrap(Exception e) {
34
35         Throwable t = unwrapAny(e);
36         if (t instanceof Exception) {
37             return (Exception) t;
38         } else if (t instanceof Error) {
39             throw (Error) t;
40         } else {
41             throw new IllegalArgumentException("Not Exception or Error: " + t);
42         }
43     }
44
45     /**
46      * Unwraps an Exception and returns the underlying Throwable.
47      *
48      * @param e is the Exception to unwrap.
49      *
50      * @return the underlying Throwable.
51      */
52     public static Throwable unwrapAny(Throwable e) {
53
54         while (true) {
55             if (e instanceof ExceptionWrapper) {
56                 Throwable e2 = ((ExceptionWrapper) e).getCause();
57                 if (e2 == null) {
58                     return e;
59                 } else {
60                     e = e2;
61                 }
62             } else {
63                 return e;
64             }
65         }
66     }
67 }