001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018import static java.util.Arrays.asList;
019import static java.util.Collections.unmodifiableList;
020import static java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.VisibleForTesting;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import java.io.IOException;
028import java.io.PrintWriter;
029import java.io.StringWriter;
030import java.lang.reflect.InvocationTargetException;
031import java.lang.reflect.Method;
032import java.util.AbstractList;
033import java.util.ArrayList;
034import java.util.Collections;
035import java.util.List;
036import javax.annotation.CheckForNull;
037
038/**
039 * Static utility methods pertaining to instances of {@link Throwable}.
040 *
041 * <p>See the Guava User Guide entry on <a
042 * href="https://github.com/google/guava/wiki/ThrowablesExplained">Throwables</a>.
043 *
044 * @author Kevin Bourrillion
045 * @author Ben Yu
046 * @since 1.0
047 */
048@GwtCompatible(emulated = true)
049@ElementTypesAreNonnullByDefault
050public final class Throwables {
051  private Throwables() {}
052
053  /**
054   * Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage:
055   *
056   * <pre>
057   * for (Foo foo : foos) {
058   *   try {
059   *     foo.bar();
060   *   } catch (BarException | RuntimeException | Error t) {
061   *     failure = t;
062   *   }
063   * }
064   * if (failure != null) {
065   *   throwIfInstanceOf(failure, BarException.class);
066   *   throwIfUnchecked(failure);
067   *   throw new AssertionError(failure);
068   * }
069   * </pre>
070   *
071   * @since 20.0
072   */
073  @GwtIncompatible // Class.cast, Class.isInstance
074  public static <X extends Throwable> void throwIfInstanceOf(
075      Throwable throwable, Class<X> declaredType) throws X {
076    checkNotNull(throwable);
077    if (declaredType.isInstance(throwable)) {
078      throw declaredType.cast(throwable);
079    }
080  }
081
082  /**
083   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code
084   * declaredType}. Example usage:
085   *
086   * <pre>
087   * try {
088   *   someMethodThatCouldThrowAnything();
089   * } catch (IKnowWhatToDoWithThisException e) {
090   *   handle(e);
091   * } catch (Throwable t) {
092   *   Throwables.propagateIfInstanceOf(t, IOException.class);
093   *   Throwables.propagateIfInstanceOf(t, SQLException.class);
094   *   throw Throwables.propagate(t);
095   * }
096   * </pre>
097   *
098   * @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code
099   *     null}.
100   */
101  @Deprecated
102  @GwtIncompatible // throwIfInstanceOf
103  public static <X extends Throwable> void propagateIfInstanceOf(
104      @CheckForNull Throwable throwable, Class<X> declaredType) throws X {
105    if (throwable != null) {
106      throwIfInstanceOf(throwable, declaredType);
107    }
108  }
109
110  /**
111   * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage:
112   *
113   * <pre>
114   * for (Foo foo : foos) {
115   *   try {
116   *     foo.bar();
117   *   } catch (RuntimeException | Error t) {
118   *     failure = t;
119   *   }
120   * }
121   * if (failure != null) {
122   *   throwIfUnchecked(failure);
123   *   throw new AssertionError(failure);
124   * }
125   * </pre>
126   *
127   * @since 20.0
128   */
129  public static void throwIfUnchecked(Throwable throwable) {
130    checkNotNull(throwable);
131    if (throwable instanceof RuntimeException) {
132      throw (RuntimeException) throwable;
133    }
134    if (throwable instanceof Error) {
135      throw (Error) throwable;
136    }
137  }
138
139  /**
140   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
141   * RuntimeException} or {@link Error}. Example usage:
142   *
143   * <pre>
144   * try {
145   *   someMethodThatCouldThrowAnything();
146   * } catch (IKnowWhatToDoWithThisException e) {
147   *   handle(e);
148   * } catch (Throwable t) {
149   *   Throwables.propagateIfPossible(t);
150   *   throw new RuntimeException("unexpected", t);
151   * }
152   * </pre>
153   *
154   * @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code
155   *     null}.
156   */
157  @Deprecated
158  @GwtIncompatible
159  public static void propagateIfPossible(@CheckForNull Throwable throwable) {
160    if (throwable != null) {
161      throwIfUnchecked(throwable);
162    }
163  }
164
165  /**
166   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
167   * RuntimeException}, {@link Error}, or {@code declaredType}. Example usage:
168   *
169   * <pre>
170   * try {
171   *   someMethodThatCouldThrowAnything();
172   * } catch (IKnowWhatToDoWithThisException e) {
173   *   handle(e);
174   * } catch (Throwable t) {
175   *   Throwables.propagateIfPossible(t, OtherException.class);
176   *   throw new RuntimeException("unexpected", t);
177   * }
178   * </pre>
179   *
180   * @param throwable the Throwable to possibly propagate
181   * @param declaredType the single checked exception type declared by the calling method
182   */
183  @GwtIncompatible // propagateIfInstanceOf
184  public static <X extends Throwable> void propagateIfPossible(
185      @CheckForNull Throwable throwable, Class<X> declaredType) throws X {
186    propagateIfInstanceOf(throwable, declaredType);
187    propagateIfPossible(throwable);
188  }
189
190  /**
191   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
192   * RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. In the
193   * unlikely case that you have three or more declared checked exception types, you can handle them
194   * all by invoking these methods repeatedly. See usage example in {@link
195   * #propagateIfPossible(Throwable, Class)}.
196   *
197   * @param throwable the Throwable to possibly propagate
198   * @param declaredType1 any checked exception type declared by the calling method
199   * @param declaredType2 any other checked exception type declared by the calling method
200   */
201  @GwtIncompatible // propagateIfInstanceOf
202  public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
203      @CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
204      throws X1, X2 {
205    checkNotNull(declaredType2);
206    propagateIfInstanceOf(throwable, declaredType1);
207    propagateIfPossible(throwable, declaredType2);
208  }
209
210  /**
211   * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link
212   * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates.
213   *
214   * <p>This method always throws an exception. The {@code RuntimeException} return type allows
215   * client code to signal to the compiler that statements after the call are unreachable. Example
216   * usage:
217   *
218   * <pre>
219   * T doSomething() {
220   *   try {
221   *     return someMethodThatCouldThrowAnything();
222   *   } catch (IKnowWhatToDoWithThisException e) {
223   *     return handle(e);
224   *   } catch (Throwable t) {
225   *     throw Throwables.propagate(t);
226   *   }
227   * }
228   * </pre>
229   *
230   * @param throwable the Throwable to propagate
231   * @return nothing will ever be returned; this return type is only for your convenience, as
232   *     illustrated in the example above
233   * @deprecated Use {@code throw e} or {@code throw new RuntimeException(e)} directly, or use a
234   *     combination of {@link #throwIfUnchecked} and {@code throw new RuntimeException(e)}. For
235   *     background on the deprecation, read <a href="https://goo.gl/Ivn2kc">Why we deprecated
236   *     {@code Throwables.propagate}</a>.
237   */
238  @CanIgnoreReturnValue
239  @GwtIncompatible
240  @Deprecated
241  public static RuntimeException propagate(Throwable throwable) {
242    throwIfUnchecked(throwable);
243    throw new RuntimeException(throwable);
244  }
245
246  /**
247   * Returns the innermost cause of {@code throwable}. The first throwable in a chain provides
248   * context from when the error or exception was initially detected. Example usage:
249   *
250   * <pre>
251   * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
252   * </pre>
253   *
254   * @throws IllegalArgumentException if there is a loop in the causal chain
255   */
256  public static Throwable getRootCause(Throwable throwable) {
257    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
258    // the slower pointer, then there's a loop.
259    Throwable slowPointer = throwable;
260    boolean advanceSlowPointer = false;
261
262    Throwable cause;
263    while ((cause = throwable.getCause()) != null) {
264      throwable = cause;
265
266      if (throwable == slowPointer) {
267        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
268      }
269      if (advanceSlowPointer) {
270        slowPointer = slowPointer.getCause();
271      }
272      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
273    }
274    return throwable;
275  }
276
277  /**
278   * Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code
279   * throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and
280   * will not reflect any subsequent changes to the cause chain.
281   *
282   * <p>Here's an example of how it can be used to find specific types of exceptions in the cause
283   * chain:
284   *
285   * <pre>
286   * Iterables.filter(Throwables.getCausalChain(e), IOException.class));
287   * </pre>
288   *
289   * @param throwable the non-null {@code Throwable} to extract causes from
290   * @return an unmodifiable list containing the cause chain starting with {@code throwable}
291   * @throws IllegalArgumentException if there is a loop in the causal chain
292   */
293  @Beta // TODO(kevinb): decide best return type
294  public static List<Throwable> getCausalChain(Throwable throwable) {
295    checkNotNull(throwable);
296    List<Throwable> causes = new ArrayList<>(4);
297    causes.add(throwable);
298
299    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
300    // the slower pointer, then there's a loop.
301    Throwable slowPointer = throwable;
302    boolean advanceSlowPointer = false;
303
304    Throwable cause;
305    while ((cause = throwable.getCause()) != null) {
306      throwable = cause;
307      causes.add(throwable);
308
309      if (throwable == slowPointer) {
310        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
311      }
312      if (advanceSlowPointer) {
313        slowPointer = slowPointer.getCause();
314      }
315      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
316    }
317    return Collections.unmodifiableList(causes);
318  }
319
320  /**
321   * Returns {@code throwable}'s cause, cast to {@code expectedCauseType}.
322   *
323   * <p>Prefer this method instead of manually casting an exception's cause. For example, {@code
324   * (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original
325   * exception {@code e} if the cause is not an {@link IOException}, but {@code
326   * Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link
327   * ClassCastException}'s cause.
328   *
329   * @throws ClassCastException if the cause cannot be cast to the expected type. The {@code
330   *     ClassCastException}'s cause is {@code throwable}.
331   * @since 22.0
332   */
333  @Beta
334  @GwtIncompatible // Class.cast(Object)
335  @CheckForNull
336  public static <X extends Throwable> X getCauseAs(
337      Throwable throwable, Class<X> expectedCauseType) {
338    try {
339      return expectedCauseType.cast(throwable.getCause());
340    } catch (ClassCastException e) {
341      e.initCause(throwable);
342      throw e;
343    }
344  }
345
346  /**
347   * Returns a string containing the result of {@link Throwable#toString() toString()}, followed by
348   * the full, recursive stack trace of {@code throwable}. Note that you probably should not be
349   * parsing the resulting string; if you need programmatic access to the stack frames, you can call
350   * {@link Throwable#getStackTrace()}.
351   */
352  @GwtIncompatible // java.io.PrintWriter, java.io.StringWriter
353  public static String getStackTraceAsString(Throwable throwable) {
354    StringWriter stringWriter = new StringWriter();
355    throwable.printStackTrace(new PrintWriter(stringWriter));
356    return stringWriter.toString();
357  }
358
359  /**
360   * Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full
361   * trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in
362   * comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace()
363   * throwable.getStackTrace()}. Note, however, that this method's special implementation is not
364   * available for all platforms and configurations. If that implementation is unavailable, this
365   * method falls back to {@code getStackTrace}. Callers that require the special implementation can
366   * check its availability with {@link #lazyStackTraceIsLazy()}.
367   *
368   * <p>The expected (but not guaranteed) performance of the special implementation differs from
369   * {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly
370   * by delaying the per-stack-frame work until each element is accessed. Roughly speaking:
371   *
372   * <ul>
373   *   <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to
374   *       retrieve each element of the returned list.
375   *   <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time
376   *       to retrieve each element of the returned list (probably slightly more than {@code
377   *       1/stackSize}).
378   * </ul>
379   *
380   * <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace
381   * throwable.setStackTrace}. Instead, it always reflects the original stack trace from the
382   * exception's creation.
383   *
384   * @since 19.0
385   */
386  // TODO(cpovirk): Say something about the possibility that List access could fail at runtime?
387  @Beta
388  @GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
389  // TODO(cpovirk): Consider making this available under GWT (slow implementation only).
390  public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
391    return lazyStackTraceIsLazy()
392        ? jlaStackTrace(throwable)
393        : unmodifiableList(asList(throwable.getStackTrace()));
394  }
395
396  /**
397   * Returns whether {@link #lazyStackTrace} will use the special implementation described in its
398   * documentation.
399   *
400   * @since 19.0
401   */
402  @Beta
403  @GwtIncompatible // getStackTraceElementMethod
404  public static boolean lazyStackTraceIsLazy() {
405    return getStackTraceElementMethod != null && getStackTraceDepthMethod != null;
406  }
407
408  @GwtIncompatible // invokeAccessibleNonThrowingMethod
409  private static List<StackTraceElement> jlaStackTrace(final Throwable t) {
410    checkNotNull(t);
411    /*
412     * TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks.
413     *
414     * TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause
415     * AOSP grief.
416     */
417    return new AbstractList<StackTraceElement>() {
418      /*
419       * The following requireNonNull calls are safe because we use jlaStackTrace() only if
420       * lazyStackTraceIsLazy() returns true.
421       */
422      @Override
423      public StackTraceElement get(int n) {
424        return (StackTraceElement)
425            invokeAccessibleNonThrowingMethod(
426                requireNonNull(getStackTraceElementMethod), requireNonNull(jla), t, n);
427      }
428
429      @Override
430      public int size() {
431        return (Integer)
432            invokeAccessibleNonThrowingMethod(
433                requireNonNull(getStackTraceDepthMethod), requireNonNull(jla), t);
434      }
435    };
436  }
437
438  @GwtIncompatible // java.lang.reflect
439  private static Object invokeAccessibleNonThrowingMethod(
440      Method method, Object receiver, Object... params) {
441    try {
442      return method.invoke(receiver, params);
443    } catch (IllegalAccessException e) {
444      throw new RuntimeException(e);
445    } catch (InvocationTargetException e) {
446      throw propagate(e.getCause());
447    }
448  }
449
450  /** JavaLangAccess class name to load using reflection */
451  @GwtIncompatible // not used by GWT emulation
452  private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
453
454  /** SharedSecrets class name to load using reflection */
455  @GwtIncompatible // not used by GWT emulation
456  @VisibleForTesting
457  static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
458
459  /** Access to some fancy internal JVM internals. */
460  @GwtIncompatible // java.lang.reflect
461  @CheckForNull
462  private static final Object jla = getJLA();
463
464  /**
465   * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
466   * find it when available. When this is null, use the slow way.
467   */
468  @GwtIncompatible // java.lang.reflect
469  @CheckForNull
470  private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod();
471
472  /**
473   * The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
474   * when available. When this is null, use the slow way.
475   */
476  @GwtIncompatible // java.lang.reflect
477  @CheckForNull
478  private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla);
479
480  /**
481   * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
482   * AppEngine, and not present in non-Sun JDKs.
483   */
484  @GwtIncompatible // java.lang.reflect
485  @CheckForNull
486  private static Object getJLA() {
487    try {
488      /*
489       * We load sun.misc.* classes using reflection since Android doesn't support these classes and
490       * would result in compilation failure if we directly refer to these classes.
491       */
492      Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null);
493      Method langAccess = sharedSecrets.getMethod("getJavaLangAccess");
494      return langAccess.invoke(null);
495    } catch (ThreadDeath death) {
496      throw death;
497    } catch (Throwable t) {
498      /*
499       * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with
500       * a NoClassDefFoundError. Other apps might deny access to sun.misc packages.
501       */
502      return null;
503    }
504  }
505
506  /**
507   * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
508   * method cannot be found (it is only to be found in fairly recent JDKs).
509   */
510  @GwtIncompatible // java.lang.reflect
511  @CheckForNull
512  private static Method getGetMethod() {
513    return getJlaMethod("getStackTraceElement", Throwable.class, int.class);
514  }
515
516  /**
517   * Returns the Method that can be used to return the size of a stack, or null if that method
518   * cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link
519   * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable)} getStackTraceDepth} prior to return it
520   * (might fail some JDKs).
521   *
522   * <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws
523   * UnsupportedOperationException</a>.
524   */
525  @GwtIncompatible // java.lang.reflect
526  @CheckForNull
527  private static Method getSizeMethod(Object jla) {
528    try {
529      Method getStackTraceDepth = getJlaMethod("getStackTraceDepth", Throwable.class);
530      if (getStackTraceDepth == null) {
531        return null;
532      }
533      getStackTraceDepth.invoke(jla, new Throwable());
534      return getStackTraceDepth;
535    } catch (UnsupportedOperationException | IllegalAccessException | InvocationTargetException e) {
536      return null;
537    }
538  }
539
540  @GwtIncompatible // java.lang.reflect
541  @CheckForNull
542  private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath {
543    try {
544      return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes);
545    } catch (ThreadDeath death) {
546      throw death;
547    } catch (Throwable t) {
548      /*
549       * Either the JavaLangAccess class itself is not found, or the method is not supported on the
550       * JVM.
551       */
552      return null;
553    }
554  }
555}