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