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 @J2ktIncompatible 074 @GwtIncompatible // Class.cast, Class.isInstance 075 public static <X extends Throwable> void throwIfInstanceOf( 076 Throwable throwable, Class<X> declaredType) throws X { 077 checkNotNull(throwable); 078 if (declaredType.isInstance(throwable)) { 079 throw declaredType.cast(throwable); 080 } 081 } 082 083 /** 084 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code 085 * declaredType}. Example usage: 086 * 087 * <pre> 088 * try { 089 * someMethodThatCouldThrowAnything(); 090 * } catch (IKnowWhatToDoWithThisException e) { 091 * handle(e); 092 * } catch (Throwable t) { 093 * Throwables.propagateIfInstanceOf(t, IOException.class); 094 * Throwables.propagateIfInstanceOf(t, SQLException.class); 095 * throw Throwables.propagate(t); 096 * } 097 * </pre> 098 * 099 * @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code 100 * null}. 101 */ 102 @Deprecated 103 @J2ktIncompatible 104 @GwtIncompatible // throwIfInstanceOf 105 public static <X extends Throwable> void propagateIfInstanceOf( 106 @CheckForNull Throwable throwable, Class<X> declaredType) throws X { 107 if (throwable != null) { 108 throwIfInstanceOf(throwable, declaredType); 109 } 110 } 111 112 /** 113 * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage: 114 * 115 * <pre> 116 * for (Foo foo : foos) { 117 * try { 118 * foo.bar(); 119 * } catch (RuntimeException | Error t) { 120 * failure = t; 121 * } 122 * } 123 * if (failure != null) { 124 * throwIfUnchecked(failure); 125 * throw new AssertionError(failure); 126 * } 127 * </pre> 128 * 129 * @since 20.0 130 */ 131 public static void throwIfUnchecked(Throwable throwable) { 132 checkNotNull(throwable); 133 if (throwable instanceof RuntimeException) { 134 throw (RuntimeException) throwable; 135 } 136 if (throwable instanceof Error) { 137 throw (Error) throwable; 138 } 139 } 140 141 /** 142 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link 143 * RuntimeException} or {@link Error}. 144 * 145 * @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code 146 * null}. 147 */ 148 @Deprecated 149 @J2ktIncompatible 150 @GwtIncompatible 151 public static void propagateIfPossible(@CheckForNull Throwable throwable) { 152 if (throwable != null) { 153 throwIfUnchecked(throwable); 154 } 155 } 156 157 /** 158 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link 159 * RuntimeException}, {@link Error}, or {@code declaredType}. 160 * 161 * <p><b>Discouraged</b> in favor of calling {@link #throwIfInstanceOf} and {@link 162 * #throwIfUnchecked}. 163 * 164 * @param throwable the Throwable to possibly propagate 165 * @param declaredType the single checked exception type declared by the calling method 166 */ 167 @J2ktIncompatible 168 @GwtIncompatible // propagateIfInstanceOf 169 public static <X extends Throwable> void propagateIfPossible( 170 @CheckForNull 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 * <p><b>Discouraged</b> in favor of calling {@link #throwIfInstanceOf} and {@link 180 * #throwIfUnchecked}. 181 * 182 * @param throwable the Throwable to possibly propagate 183 * @param declaredType1 any checked exception type declared by the calling method 184 * @param declaredType2 any other checked exception type declared by the calling method 185 */ 186 @J2ktIncompatible 187 @GwtIncompatible // propagateIfInstanceOf 188 public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible( 189 @CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) 190 throws X1, X2 { 191 checkNotNull(declaredType2); 192 propagateIfInstanceOf(throwable, declaredType1); 193 propagateIfPossible(throwable, declaredType2); 194 } 195 196 /** 197 * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link 198 * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates. 199 * 200 * <p>This method always throws an exception. The {@code RuntimeException} return type allows 201 * client code to signal to the compiler that statements after the call are unreachable. Example 202 * usage: 203 * 204 * <pre> 205 * T doSomething() { 206 * try { 207 * return someMethodThatCouldThrowAnything(); 208 * } catch (IKnowWhatToDoWithThisException e) { 209 * return handle(e); 210 * } catch (Throwable t) { 211 * throw Throwables.propagate(t); 212 * } 213 * } 214 * </pre> 215 * 216 * @param throwable the Throwable to propagate 217 * @return nothing will ever be returned; this return type is only for your convenience, as 218 * illustrated in the example above 219 * @deprecated To preserve behavior, use {@code throw e} or {@code throw new RuntimeException(e)} 220 * directly, or use a combination of {@link #throwIfUnchecked} and {@code throw new 221 * RuntimeException(e)}. But consider whether users would be better off if your API threw a 222 * different type of exception. For background on the deprecation, read <a 223 * href="https://goo.gl/Ivn2kc">Why we deprecated {@code Throwables.propagate}</a>. 224 */ 225 @CanIgnoreReturnValue 226 @J2ktIncompatible 227 @GwtIncompatible 228 @Deprecated 229 public static RuntimeException propagate(Throwable throwable) { 230 throwIfUnchecked(throwable); 231 throw new RuntimeException(throwable); 232 } 233 234 /** 235 * Returns the innermost cause of {@code throwable}. The first throwable in a chain provides 236 * context from when the error or exception was initially detected. Example usage: 237 * 238 * <pre> 239 * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage()); 240 * </pre> 241 * 242 * @throws IllegalArgumentException if there is a loop in the causal chain 243 */ 244 public static Throwable getRootCause(Throwable throwable) { 245 // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches 246 // the slower pointer, then there's a loop. 247 Throwable slowPointer = throwable; 248 boolean advanceSlowPointer = false; 249 250 Throwable cause; 251 while ((cause = throwable.getCause()) != null) { 252 throwable = cause; 253 254 if (throwable == slowPointer) { 255 throw new IllegalArgumentException("Loop in causal chain detected.", throwable); 256 } 257 if (advanceSlowPointer) { 258 slowPointer = slowPointer.getCause(); 259 } 260 advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration 261 } 262 return throwable; 263 } 264 265 /** 266 * Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code 267 * throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and 268 * will not reflect any subsequent changes to the cause chain. 269 * 270 * <p>Here's an example of how it can be used to find specific types of exceptions in the cause 271 * chain: 272 * 273 * <pre> 274 * Iterables.filter(Throwables.getCausalChain(e), IOException.class)); 275 * </pre> 276 * 277 * @param throwable the non-null {@code Throwable} to extract causes from 278 * @return an unmodifiable list containing the cause chain starting with {@code throwable} 279 * @throws IllegalArgumentException if there is a loop in the causal chain 280 */ 281 public static List<Throwable> getCausalChain(Throwable throwable) { 282 checkNotNull(throwable); 283 List<Throwable> causes = new ArrayList<>(4); 284 causes.add(throwable); 285 286 // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches 287 // the slower pointer, then there's a loop. 288 Throwable slowPointer = throwable; 289 boolean advanceSlowPointer = false; 290 291 Throwable cause; 292 while ((cause = throwable.getCause()) != null) { 293 throwable = cause; 294 causes.add(throwable); 295 296 if (throwable == slowPointer) { 297 throw new IllegalArgumentException("Loop in causal chain detected.", throwable); 298 } 299 if (advanceSlowPointer) { 300 slowPointer = slowPointer.getCause(); 301 } 302 advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration 303 } 304 return Collections.unmodifiableList(causes); 305 } 306 307 /** 308 * Returns {@code throwable}'s cause, cast to {@code expectedCauseType}. 309 * 310 * <p>Prefer this method instead of manually casting an exception's cause. For example, {@code 311 * (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original 312 * exception {@code e} if the cause is not an {@link IOException}, but {@code 313 * Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link 314 * ClassCastException}'s cause. 315 * 316 * @throws ClassCastException if the cause cannot be cast to the expected type. The {@code 317 * ClassCastException}'s cause is {@code throwable}. 318 * @since 22.0 319 */ 320 @J2ktIncompatible 321 @GwtIncompatible // Class.cast(Object) 322 @CheckForNull 323 public static <X extends Throwable> 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 456 @GwtIncompatible // java.lang.reflect 457 @CheckForNull 458 private static final Object jla = getJLA(); 459 460 /** 461 * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to 462 * find it when available. When this is null, use the slow way. 463 */ 464 @J2ktIncompatible 465 @GwtIncompatible // java.lang.reflect 466 @CheckForNull 467 private static final Method getStackTraceElementMethod = (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 474 @GwtIncompatible // java.lang.reflect 475 @CheckForNull 476 private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla); 477 478 /** 479 * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in 480 * AppEngine, and not present in non-Sun JDKs. 481 */ 482 @J2ktIncompatible 483 @GwtIncompatible // java.lang.reflect 484 @CheckForNull 485 private static Object getJLA() { 486 try { 487 /* 488 * We load sun.misc.* classes using reflection since Android doesn't support these classes and 489 * would result in compilation failure if we directly refer to these classes. 490 */ 491 Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null); 492 Method langAccess = sharedSecrets.getMethod("getJavaLangAccess"); 493 return langAccess.invoke(null); 494 } catch (ThreadDeath death) { 495 throw death; 496 } catch (Throwable t) { 497 /* 498 * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with 499 * a NoClassDefFoundError. Other apps might deny access to sun.misc packages. 500 */ 501 return null; 502 } 503 } 504 505 /** 506 * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that 507 * method cannot be found (it is only to be found in fairly recent JDKs). 508 */ 509 @J2ktIncompatible 510 @GwtIncompatible // java.lang.reflect 511 @CheckForNull 512 private static Method getGetMethod() { 513 return getJlaMethod("getStackTraceElement", Throwable.class, int.class); 514 } 515 516 /** 517 * Returns the Method that can be used to return the size of a stack, or null if that method 518 * cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link 519 * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable) getStackTraceDepth} prior to return it 520 * (might fail some JDKs). 521 * 522 * <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws 523 * UnsupportedOperationException</a>. 524 */ 525 @J2ktIncompatible 526 @GwtIncompatible // java.lang.reflect 527 @CheckForNull 528 private static Method getSizeMethod(Object jla) { 529 try { 530 Method getStackTraceDepth = getJlaMethod("getStackTraceDepth", Throwable.class); 531 if (getStackTraceDepth == null) { 532 return null; 533 } 534 getStackTraceDepth.invoke(jla, new Throwable()); 535 return getStackTraceDepth; 536 } catch (UnsupportedOperationException | IllegalAccessException | InvocationTargetException e) { 537 return null; 538 } 539 } 540 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}