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.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.annotations.J2ktIncompatible;
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  @J2ktIncompatible
103  @GwtIncompatible // throwIfInstanceOf
104  public static <X extends Throwable> void propagateIfInstanceOf(
105      @CheckForNull Throwable throwable, Class<X> declaredType) throws X {
106    if (throwable != null) {
107      throwIfInstanceOf(throwable, declaredType);
108    }
109  }
110
111  /**
112   * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage:
113   *
114   * <pre>
115   * for (Foo foo : foos) {
116   *   try {
117   *     foo.bar();
118   *   } catch (RuntimeException | Error t) {
119   *     failure = t;
120   *   }
121   * }
122   * if (failure != null) {
123   *   throwIfUnchecked(failure);
124   *   throw new AssertionError(failure);
125   * }
126   * </pre>
127   *
128   * @since 20.0
129   */
130  public static void throwIfUnchecked(Throwable throwable) {
131    checkNotNull(throwable);
132    if (throwable instanceof RuntimeException) {
133      throw (RuntimeException) throwable;
134    }
135    if (throwable instanceof Error) {
136      throw (Error) throwable;
137    }
138  }
139
140  /**
141   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
142   * RuntimeException} or {@link Error}.
143   *
144   * @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code
145   *     null}.
146   */
147  @Deprecated
148  @J2ktIncompatible
149  @GwtIncompatible
150  public static void propagateIfPossible(@CheckForNull Throwable throwable) {
151    if (throwable != null) {
152      throwIfUnchecked(throwable);
153    }
154  }
155
156  /**
157   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
158   * RuntimeException}, {@link Error}, or {@code declaredType}.
159   *
160   * <p><b>Discouraged</b> in favor of calling {@link #throwIfInstanceOf} and {@link
161   * #throwIfUnchecked}.
162   *
163   * @param throwable the Throwable to possibly propagate
164   * @param declaredType the single checked exception type declared by the calling method
165   */
166  @J2ktIncompatible
167  @GwtIncompatible // propagateIfInstanceOf
168  public static <X extends Throwable> void propagateIfPossible(
169      @CheckForNull Throwable throwable, Class<X> declaredType) throws X {
170    propagateIfInstanceOf(throwable, declaredType);
171    propagateIfPossible(throwable);
172  }
173
174  /**
175   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
176   * RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}.
177   *
178   * <p><b>Discouraged</b> in favor of calling {@link #throwIfInstanceOf} and {@link
179   * #throwIfUnchecked}.
180   *
181   * @param throwable the Throwable to possibly propagate
182   * @param declaredType1 any checked exception type declared by the calling method
183   * @param declaredType2 any other checked exception type declared by the calling method
184   */
185  @J2ktIncompatible
186  @GwtIncompatible // propagateIfInstanceOf
187  public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
188      @CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
189      throws X1, X2 {
190    checkNotNull(declaredType2);
191    propagateIfInstanceOf(throwable, declaredType1);
192    propagateIfPossible(throwable, declaredType2);
193  }
194
195  /**
196   * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link
197   * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates.
198   *
199   * <p>This method always throws an exception. The {@code RuntimeException} return type allows
200   * client code to signal to the compiler that statements after the call are unreachable. Example
201   * usage:
202   *
203   * <pre>
204   * T doSomething() {
205   *   try {
206   *     return someMethodThatCouldThrowAnything();
207   *   } catch (IKnowWhatToDoWithThisException e) {
208   *     return handle(e);
209   *   } catch (Throwable t) {
210   *     throw Throwables.propagate(t);
211   *   }
212   * }
213   * </pre>
214   *
215   * @param throwable the Throwable to propagate
216   * @return nothing will ever be returned; this return type is only for your convenience, as
217   *     illustrated in the example above
218   * @deprecated To preserve behavior, use {@code throw e} or {@code throw new RuntimeException(e)}
219   *     directly, or use a combination of {@link #throwIfUnchecked} and {@code throw new
220   *     RuntimeException(e)}. But consider whether users would be better off if your API threw a
221   *     different type of exception. For background on the deprecation, read <a
222   *     href="https://goo.gl/Ivn2kc">Why we deprecated {@code Throwables.propagate}</a>.
223   */
224  @CanIgnoreReturnValue
225  @J2ktIncompatible
226  @GwtIncompatible
227  @Deprecated
228  public static RuntimeException propagate(Throwable throwable) {
229    throwIfUnchecked(throwable);
230    throw new RuntimeException(throwable);
231  }
232
233  /**
234   * Returns the innermost cause of {@code throwable}. The first throwable in a chain provides
235   * context from when the error or exception was initially detected. Example usage:
236   *
237   * <pre>
238   * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
239   * </pre>
240   *
241   * @throws IllegalArgumentException if there is a loop in the causal chain
242   */
243  public static Throwable getRootCause(Throwable throwable) {
244    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
245    // the slower pointer, then there's a loop.
246    Throwable slowPointer = throwable;
247    boolean advanceSlowPointer = false;
248
249    Throwable cause;
250    while ((cause = throwable.getCause()) != null) {
251      throwable = cause;
252
253      if (throwable == slowPointer) {
254        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
255      }
256      if (advanceSlowPointer) {
257        slowPointer = slowPointer.getCause();
258      }
259      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
260    }
261    return throwable;
262  }
263
264  /**
265   * Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code
266   * throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and
267   * will not reflect any subsequent changes to the cause chain.
268   *
269   * <p>Here's an example of how it can be used to find specific types of exceptions in the cause
270   * chain:
271   *
272   * <pre>
273   * Iterables.filter(Throwables.getCausalChain(e), IOException.class));
274   * </pre>
275   *
276   * @param throwable the non-null {@code Throwable} to extract causes from
277   * @return an unmodifiable list containing the cause chain starting with {@code throwable}
278   * @throws IllegalArgumentException if there is a loop in the causal chain
279   */
280  public static List<Throwable> getCausalChain(Throwable throwable) {
281    checkNotNull(throwable);
282    List<Throwable> causes = new ArrayList<>(4);
283    causes.add(throwable);
284
285    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
286    // the slower pointer, then there's a loop.
287    Throwable slowPointer = throwable;
288    boolean advanceSlowPointer = false;
289
290    Throwable cause;
291    while ((cause = throwable.getCause()) != null) {
292      throwable = cause;
293      causes.add(throwable);
294
295      if (throwable == slowPointer) {
296        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
297      }
298      if (advanceSlowPointer) {
299        slowPointer = slowPointer.getCause();
300      }
301      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
302    }
303    return Collections.unmodifiableList(causes);
304  }
305
306  /**
307   * Returns {@code throwable}'s cause, cast to {@code expectedCauseType}.
308   *
309   * <p>Prefer this method instead of manually casting an exception's cause. For example, {@code
310   * (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original
311   * exception {@code e} if the cause is not an {@link IOException}, but {@code
312   * Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link
313   * ClassCastException}'s cause.
314   *
315   * @throws ClassCastException if the cause cannot be cast to the expected type. The {@code
316   *     ClassCastException}'s cause is {@code throwable}.
317   * @since 22.0
318   */
319  @GwtIncompatible // Class.cast(Object)
320  @CheckForNull
321  public static <X extends Throwable> X getCauseAs(
322      Throwable throwable, Class<X> expectedCauseType) {
323    try {
324      return expectedCauseType.cast(throwable.getCause());
325    } catch (ClassCastException e) {
326      e.initCause(throwable);
327      throw e;
328    }
329  }
330
331  /**
332   * Returns a string containing the result of {@link Throwable#toString() toString()}, followed by
333   * the full, recursive stack trace of {@code throwable}. Note that you probably should not be
334   * parsing the resulting string; if you need programmatic access to the stack frames, you can call
335   * {@link Throwable#getStackTrace()}.
336   */
337  @GwtIncompatible // java.io.PrintWriter, java.io.StringWriter
338  public static String getStackTraceAsString(Throwable throwable) {
339    StringWriter stringWriter = new StringWriter();
340    throwable.printStackTrace(new PrintWriter(stringWriter));
341    return stringWriter.toString();
342  }
343
344  /**
345   * Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full
346   * trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in
347   * comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace()
348   * throwable.getStackTrace()}. Note, however, that this method's special implementation is not
349   * available for all platforms and configurations. If that implementation is unavailable, this
350   * method falls back to {@code getStackTrace}. Callers that require the special implementation can
351   * check its availability with {@link #lazyStackTraceIsLazy()}.
352   *
353   * <p>The expected (but not guaranteed) performance of the special implementation differs from
354   * {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly
355   * by delaying the per-stack-frame work until each element is accessed. Roughly speaking:
356   *
357   * <ul>
358   *   <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to
359   *       retrieve each element of the returned list.
360   *   <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time
361   *       to retrieve each element of the returned list (probably slightly more than {@code
362   *       1/stackSize}).
363   * </ul>
364   *
365   * <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace
366   * throwable.setStackTrace}. Instead, it always reflects the original stack trace from the
367   * exception's creation.
368   *
369   * @since 19.0
370   * @deprecated This method is equivalent to {@link Throwable#getStackTrace()} on JDK versions past
371   *     JDK 8 and on all Android versions. Use {@link Throwable#getStackTrace()} directly, or where
372   *     possible use the {@code java.lang.StackWalker.walk} method introduced in JDK 9.
373   */
374  @Deprecated
375  @J2ktIncompatible
376  @GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
377  public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
378    return lazyStackTraceIsLazy()
379        ? jlaStackTrace(throwable)
380        : unmodifiableList(asList(throwable.getStackTrace()));
381  }
382
383  /**
384   * Returns whether {@link #lazyStackTrace} will use the special implementation described in its
385   * documentation.
386   *
387   * @since 19.0
388   * @deprecated This method always returns false on JDK versions past JDK 8 and on all Android
389   *     versions.
390   */
391  @Deprecated
392  @J2ktIncompatible
393  @GwtIncompatible // getStackTraceElementMethod
394  public static boolean lazyStackTraceIsLazy() {
395    return getStackTraceElementMethod != null && getStackTraceDepthMethod != null;
396  }
397
398  @J2ktIncompatible
399  @GwtIncompatible // invokeAccessibleNonThrowingMethod
400  private static List<StackTraceElement> jlaStackTrace(Throwable t) {
401    checkNotNull(t);
402    /*
403     * TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks.
404     *
405     * TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause
406     * AOSP grief.
407     */
408    return new AbstractList<StackTraceElement>() {
409      /*
410       * The following requireNonNull calls are safe because we use jlaStackTrace() only if
411       * lazyStackTraceIsLazy() returns true.
412       */
413      @Override
414      public StackTraceElement get(int n) {
415        return (StackTraceElement)
416            invokeAccessibleNonThrowingMethod(
417                requireNonNull(getStackTraceElementMethod), requireNonNull(jla), t, n);
418      }
419
420      @Override
421      public int size() {
422        return (Integer)
423            invokeAccessibleNonThrowingMethod(
424                requireNonNull(getStackTraceDepthMethod), requireNonNull(jla), t);
425      }
426    };
427  }
428
429  @J2ktIncompatible
430  @GwtIncompatible // java.lang.reflect
431  private static Object invokeAccessibleNonThrowingMethod(
432      Method method, Object receiver, Object... params) {
433    try {
434      return method.invoke(receiver, params);
435    } catch (IllegalAccessException e) {
436      throw new RuntimeException(e);
437    } catch (InvocationTargetException e) {
438      throw propagate(e.getCause());
439    }
440  }
441
442  /** JavaLangAccess class name to load using reflection */
443  @J2ktIncompatible @GwtIncompatible // not used by GWT emulation
444  private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
445
446  /** SharedSecrets class name to load using reflection */
447  @J2ktIncompatible
448  @GwtIncompatible // not used by GWT emulation
449  @VisibleForTesting
450  static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
451
452  /** Access to some fancy internal JVM internals. */
453  @J2ktIncompatible
454  @GwtIncompatible // java.lang.reflect
455  @CheckForNull
456  private static final Object jla = getJLA();
457
458  /**
459   * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
460   * find it when available. When this is null, use the slow way.
461   */
462  @J2ktIncompatible
463  @GwtIncompatible // java.lang.reflect
464  @CheckForNull
465  private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod();
466
467  /**
468   * The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
469   * when available. When this is null, use the slow way.
470   */
471  @J2ktIncompatible
472  @GwtIncompatible // java.lang.reflect
473  @CheckForNull
474  private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla);
475
476  /**
477   * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in
478   * AppEngine, and not present in non-Sun JDKs.
479   */
480  @SuppressWarnings("removal") // b/318391980
481  @J2ktIncompatible
482  @GwtIncompatible // java.lang.reflect
483  @CheckForNull
484  private static Object getJLA() {
485    try {
486      /*
487       * We load sun.misc.* classes using reflection since Android doesn't support these classes and
488       * would result in compilation failure if we directly refer to these classes.
489       */
490      Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null);
491      Method langAccess = sharedSecrets.getMethod("getJavaLangAccess");
492      return langAccess.invoke(null);
493    } catch (ThreadDeath death) {
494      throw death;
495    } catch (Throwable t) {
496      /*
497       * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with
498       * a NoClassDefFoundError. Other apps might deny access to sun.misc packages.
499       */
500      return null;
501    }
502  }
503
504  /**
505   * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
506   * method cannot be found (it is only to be found in fairly recent JDKs).
507   */
508  @J2ktIncompatible
509  @GwtIncompatible // java.lang.reflect
510  @CheckForNull
511  private static Method getGetMethod() {
512    return getJlaMethod("getStackTraceElement", Throwable.class, int.class);
513  }
514
515  /**
516   * Returns the Method that can be used to return the size of a stack, or null if that method
517   * cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link
518   * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable) getStackTraceDepth} prior to return it
519   * (might fail some JDKs).
520   *
521   * <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws
522   * UnsupportedOperationException</a>.
523   */
524  @J2ktIncompatible
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  @SuppressWarnings("removal") // b/318391980
541  @J2ktIncompatible
542  @GwtIncompatible // java.lang.reflect
543  @CheckForNull
544  private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath {
545    try {
546      return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes);
547    } catch (ThreadDeath death) {
548      throw death;
549    } catch (Throwable t) {
550      /*
551       * Either the JavaLangAccess class itself is not found, or the method is not supported on the
552       * JVM.
553       */
554      return null;
555    }
556  }
557}