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