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