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