Static utility methods pertaining to instances of Throwable. See the Guava User Guide entry on Throwables . @author Kevin Bourrillion @author Ben Yu @since 1.0
| 45 | |
| 46 | |
| 47 | @GwtCompatible(emulated = true) |
| 48 | public final class Throwables { |
| 49 | private Throwables() {} |
| 50 | |
| 51 | /** |
| 52 | * Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage: |
| 53 | * |
| 54 | * <pre> |
| 55 | * for (Foo foo : foos) { |
| 56 | * try { |
| 57 | * foo.bar(); |
| 58 | * } catch (BarException | RuntimeException | Error t) { |
| 59 | * failure = t; |
| 60 | * } |
| 61 | * } |
| 62 | * if (failure != null) { |
| 63 | * throwIfInstanceOf(failure, BarException.class); |
| 64 | * throwIfUnchecked(failure); |
| 65 | * throw new AssertionError(failure); |
| 66 | * } |
| 67 | * </pre> |
| 68 | * |
| 69 | * @since 20.0 |
| 70 | */ |
| 71 | |
| 72 | |
| 73 | @GwtIncompatible // Class.cast, Class.isInstance |
| 74 | public static <X extends Throwable> void throwIfInstanceOf(Throwable throwable, Class<X> declaredType) |
| 75 | throws X { |
| 76 | checkNotNull(throwable); |
| 77 | if (declaredType.isInstance(throwable)) { |
| 78 | throw declaredType.cast(throwable); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code |
| 84 | * declaredType}. Example usage: |
| 85 | * |
| 86 | * <pre> |
| 87 | * try { |
| 88 | * someMethodThatCouldThrowAnything(); |
| 89 | * } catch (IKnowWhatToDoWithThisException e) { |
| 90 | * handle(e); |
| 91 | * } catch (Throwable t) { |
| 92 | * Throwables.propagateIfInstanceOf(t, IOException.class); |
| 93 | * Throwables.propagateIfInstanceOf(t, SQLException.class); |
| 94 | * throw Throwables.propagate(t); |
| 95 | * } |
| 96 | * </pre> |
| 97 | * |
| 98 | * @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior |
| 99 | * but rejects {@code null}. This method is scheduled to be removed in July 2018. |
| 100 | */ |
| 101 | |
| 102 | @Deprecated |
| 103 | @GwtIncompatible // throwIfInstanceOf |
| 104 | public static <X extends Throwable> void propagateIfInstanceOf(@Nullable Throwable throwable, Class<X> declaredType) |
nothing calls this directly
no test coverage detected