001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.base;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static java.util.Arrays.asList;
021import static java.util.Collections.unmodifiableList;
022
023import com.google.common.annotations.Beta;
024import com.google.common.annotations.VisibleForTesting;
025
026import java.io.PrintWriter;
027import java.io.StringWriter;
028import java.lang.reflect.InvocationTargetException;
029import java.lang.reflect.Method;
030import java.util.AbstractList;
031import java.util.ArrayList;
032import java.util.Collections;
033import java.util.List;
034
035import javax.annotation.CheckReturnValue;
036import javax.annotation.Nullable;
037
038/**
039 * Static utility methods pertaining to instances of {@link Throwable}.
040 *
041 * <p>See the Guava User Guide entry on <a href=
042 * "https://github.com/google/guava/wiki/ThrowablesExplained">Throwables</a>.
043 *
044 * @author Kevin Bourrillion
045 * @author Ben Yu
046 * @since 1.0
047 */
048public final class Throwables {
049  private Throwables() {}
050
051  /**
052   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code
053   * declaredType}.  Example usage:
054   * <pre>
055   *   try {
056   *     someMethodThatCouldThrowAnything();
057   *   } catch (IKnowWhatToDoWithThisException e) {
058   *     handle(e);
059   *   } catch (Throwable t) {
060   *     Throwables.propagateIfInstanceOf(t, IOException.class);
061   *     Throwables.propagateIfInstanceOf(t, SQLException.class);
062   *     throw Throwables.propagate(t);
063   *   }
064   * </pre>
065   */
066  public static <X extends Throwable> void propagateIfInstanceOf(
067      @Nullable Throwable throwable, Class<X> declaredType) throws X {
068    // Check for null is needed to avoid frequent JNI calls to isInstance().
069    if (throwable != null && declaredType.isInstance(throwable)) {
070      throw declaredType.cast(throwable);
071    }
072  }
073
074  /**
075   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
076   * RuntimeException} or {@link Error}.  Example usage:
077   * <pre>
078   *   try {
079   *     someMethodThatCouldThrowAnything();
080   *   } catch (IKnowWhatToDoWithThisException e) {
081   *     handle(e);
082   *   } catch (Throwable t) {
083   *     Throwables.propagateIfPossible(t);
084   *     throw new RuntimeException("unexpected", t);
085   *   }
086   * </pre>
087   */
088  public static void propagateIfPossible(@Nullable Throwable throwable) {
089    propagateIfInstanceOf(throwable, Error.class);
090    propagateIfInstanceOf(throwable, RuntimeException.class);
091  }
092
093  /**
094   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
095   * RuntimeException}, {@link Error}, or {@code declaredType}. Example usage:
096   * <pre>
097   *   try {
098   *     someMethodThatCouldThrowAnything();
099   *   } catch (IKnowWhatToDoWithThisException e) {
100   *     handle(e);
101   *   } catch (Throwable t) {
102   *     Throwables.propagateIfPossible(t, OtherException.class);
103   *     throw new RuntimeException("unexpected", t);
104   *   }
105   * </pre>
106   *
107   * @param throwable the Throwable to possibly propagate
108   * @param declaredType the single checked exception type declared by the calling method
109   */
110  public static <X extends Throwable> void propagateIfPossible(
111      @Nullable Throwable throwable, Class<X> declaredType) throws X {
112    propagateIfInstanceOf(throwable, declaredType);
113    propagateIfPossible(throwable);
114  }
115
116  /**
117   * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
118   * RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. In the
119   * unlikely case that you have three or more declared checked exception types, you can handle them
120   * all by invoking these methods repeatedly. See usage example in {@link
121   * #propagateIfPossible(Throwable, Class)}.
122   *
123   * @param throwable the Throwable to possibly propagate
124   * @param declaredType1 any checked exception type declared by the calling method
125   * @param declaredType2 any other checked exception type declared by the calling method
126   */
127  public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
128      @Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
129      throws X1, X2 {
130    checkNotNull(declaredType2);
131    propagateIfInstanceOf(throwable, declaredType1);
132    propagateIfPossible(throwable, declaredType2);
133  }
134
135  /**
136   * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link
137   * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates.
138   * <p>
139   * This method always throws an exception. The {@code RuntimeException} return type is only for
140   * client code to make Java type system happy in case a return value is required by the enclosing
141   * method. Example usage:
142   * <pre>
143   *   T doSomething() {
144   *     try {
145   *       return someMethodThatCouldThrowAnything();
146   *     } catch (IKnowWhatToDoWithThisException e) {
147   *       return handle(e);
148   *     } catch (Throwable t) {
149   *       throw Throwables.propagate(t);
150   *     }
151   *   }
152   * </pre>
153   *
154   * @param throwable the Throwable to propagate
155   * @return nothing will ever be returned; this return type is only for your convenience, as
156   *     illustrated in the example above
157   */
158  public static RuntimeException propagate(Throwable throwable) {
159    propagateIfPossible(checkNotNull(throwable));
160    throw new RuntimeException(throwable);
161  }
162
163  /**
164   * Returns the innermost cause of {@code throwable}. The first throwable in a
165   * chain provides context from when the error or exception was initially
166   * detected. Example usage:
167   * <pre>
168   *   assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
169   * </pre>
170   */
171  @CheckReturnValue
172  public static Throwable getRootCause(Throwable throwable) {
173    Throwable cause;
174    while ((cause = throwable.getCause()) != null) {
175      throwable = cause;
176    }
177    return throwable;
178  }
179
180  /**
181   * Gets a {@code Throwable} cause chain as a list.  The first entry in the list will be {@code
182   * throwable} followed by its cause hierarchy.  Note that this is a snapshot of the cause chain
183   * and will not reflect any subsequent changes to the cause chain.
184   *
185   * <p>Here's an example of how it can be used to find specific types of exceptions in the cause
186   * chain:
187   *
188   * <pre>
189   * Iterables.filter(Throwables.getCausalChain(e), IOException.class));
190   * </pre>
191   *
192   * @param throwable the non-null {@code Throwable} to extract causes from
193   * @return an unmodifiable list containing the cause chain starting with {@code throwable}
194   */
195  @Beta // TODO(kevinb): decide best return type
196  @CheckReturnValue
197  public static List<Throwable> getCausalChain(Throwable throwable) {
198    checkNotNull(throwable);
199    List<Throwable> causes = new ArrayList<Throwable>(4);
200    while (throwable != null) {
201      causes.add(throwable);
202      throwable = throwable.getCause();
203    }
204    return Collections.unmodifiableList(causes);
205  }
206
207  /**
208   * Returns a string containing the result of {@link Throwable#toString() toString()}, followed by
209   * the full, recursive stack trace of {@code throwable}. Note that you probably should not be
210   * parsing the resulting string; if you need programmatic access to the stack frames, you can call
211   * {@link Throwable#getStackTrace()}.
212   */
213  @CheckReturnValue
214  public static String getStackTraceAsString(Throwable throwable) {
215    StringWriter stringWriter = new StringWriter();
216    throwable.printStackTrace(new PrintWriter(stringWriter));
217    return stringWriter.toString();
218  }
219
220  /**
221   * Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full
222   * trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in
223   * comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace()
224   * throwable.getStackTrace()}. Note, however, that this method's special implementation is not
225   * available for all platforms and configurations. If that implementation is unavailable, this
226   * method falls back to {@code getStackTrace}. Callers that require the special implementation can
227   * check its availability with {@link #lazyStackTraceIsLazy()}.
228   *
229   * <p>The expected (but not guaranteed) performance of the special implementation differs from
230   * {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly
231   * by delaying the per-stack-frame work until each element is accessed. Roughly speaking:
232   *
233   * <ul>
234   * <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to
235   * retrieve each element of the returned list.
236   * <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time to
237   * retrieve each element of the returned list (probably slightly more than {@code 1/stackSize}).
238   * </ul>
239   *
240   * <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace
241   * throwable.setStackTrace}. Instead, it always reflects the original stack trace from the
242   * exception's creation.
243   *
244   * @since 19.0
245   */
246  // TODO(cpovirk): Say something about the possibility that List access could fail at runtime?
247  @Beta
248  @CheckReturnValue
249  public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
250    return lazyStackTraceIsLazy()
251        ? jlaStackTrace(throwable)
252        : unmodifiableList(asList(throwable.getStackTrace()));
253  }
254
255  /**
256   * Returns whether {@link #lazyStackTrace} will use the special implementation described in its
257   * documentation.
258   *
259   * @since 19.0
260   */
261  @Beta
262  @CheckReturnValue
263  public static boolean lazyStackTraceIsLazy() {
264    return getStackTraceElementMethod != null & getStackTraceDepthMethod != null;
265  }
266
267  private static List<StackTraceElement> jlaStackTrace(final Throwable t) {
268    checkNotNull(t);
269    /*
270     * TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks.
271     *
272     * TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause
273     * AOSP grief.
274     */
275    return new AbstractList<StackTraceElement>() {
276      @Override
277      public StackTraceElement get(int n) {
278        return (StackTraceElement)
279            invokeAccessibleNonThrowingMethod(getStackTraceElementMethod, jla, t, n);
280      }
281
282      @Override
283      public int size() {
284        return (Integer) invokeAccessibleNonThrowingMethod(getStackTraceDepthMethod, jla, t);
285      }
286    };
287  }
288
289  private static Object invokeAccessibleNonThrowingMethod(
290      Method method, Object receiver, Object... params) {
291    try {
292      return method.invoke(receiver, params);
293    } catch (IllegalAccessException e) {
294      throw new RuntimeException(e);
295    } catch (InvocationTargetException e) {
296      throw propagate(e.getCause());
297    }
298  }
299
300  /** JavaLangAccess class name to load using reflection */
301  private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess";
302
303  /** SharedSecrets class name to load using reflection */
304  @VisibleForTesting static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets";
305
306  /** Access to some fancy internal JVM internals. */
307  @Nullable private static final Object jla = getJLA();
308
309  /**
310   * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to
311   * find it when available. When this is null, use the slow way.
312   */
313  @Nullable
314  private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod();
315
316  /**
317   * The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it
318   * when available. When this is null, use the slow way.
319   */
320  @Nullable
321  private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod();
322
323  /**
324   * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not whitelisted for
325   * AppEngine, and not present in non-Sun JDKs.
326   */
327  @Nullable
328  private static Object getJLA() {
329    try {
330      /*
331       * We load sun.misc.* classes using reflection since Android doesn't support these classes and
332       * would result in compilation failure if we directly refer to these classes.
333       */
334      Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null);
335      Method langAccess = sharedSecrets.getMethod("getJavaLangAccess");
336      return langAccess.invoke(null);
337    } catch (ThreadDeath death) {
338      throw death;
339    } catch (Throwable t) {
340      /*
341       * This is not one of AppEngine's whitelisted classes, so even in Sun JDKs, this can fail with
342       * a NoClassDefFoundError. Other apps might deny access to sun.misc packages.
343       */
344      return null;
345    }
346  }
347
348  /**
349   * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that
350   * method cannot be found (it is only to be found in fairly recent JDKs).
351   */
352  @Nullable
353  private static Method getGetMethod() {
354    return getJlaMethod("getStackTraceElement", Throwable.class, int.class);
355  }
356
357  /**
358   * Returns the Method that can be used to return the size of a stack, or null if that method
359   * cannot be found (it is only to be found in fairly recent JDKs).
360   */
361  @Nullable
362  private static Method getSizeMethod() {
363    return getJlaMethod("getStackTraceDepth", Throwable.class);
364  }
365
366  @Nullable
367  private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath {
368    try {
369      return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes);
370    } catch (ThreadDeath death) {
371      throw death;
372    } catch (Throwable t) {
373      /*
374       * Either the JavaLangAccess class itself is not found, or the method is not supported on the
375       * JVM.
376       */
377      return null;
378    }
379  }
380}