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