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; 020 021import com.google.common.annotations.Beta; 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.Nullable; 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) 048public final class Throwables { 049 private Throwables() {} 050 051 /** 052 * Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage: 053 * 054 * <pre> 055 * for (Foo foo : foos) { 056 * try { 057 * foo.bar(); 058 * } catch (BarException | RuntimeException | Error t) { 059 * failure = t; 060 * } 061 * } 062 * if (failure != null) { 063 * throwIfInstanceOf(failure, BarException.class); 064 * throwIfUnchecked(failure); 065 * throw new AssertionError(failure); 066 * } 067 * </pre> 068 * 069 * @since 20.0 070 */ 071 @GwtIncompatible // Class.cast, Class.isInstance 072 public static <X extends Throwable> void throwIfInstanceOf( 073 Throwable throwable, Class<X> declaredType) throws X { 074 checkNotNull(throwable); 075 if (declaredType.isInstance(throwable)) { 076 throw declaredType.cast(throwable); 077 } 078 } 079 080 /** 081 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code 082 * declaredType}. Example usage: 083 * 084 * <pre> 085 * try { 086 * someMethodThatCouldThrowAnything(); 087 * } catch (IKnowWhatToDoWithThisException e) { 088 * handle(e); 089 * } catch (Throwable t) { 090 * Throwables.propagateIfInstanceOf(t, IOException.class); 091 * Throwables.propagateIfInstanceOf(t, SQLException.class); 092 * throw Throwables.propagate(t); 093 * } 094 * </pre> 095 * 096 * @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code 097 * null}. This method is scheduled to be removed in July 2018. 098 */ 099 @Deprecated 100 @GwtIncompatible // throwIfInstanceOf 101 public static <X extends Throwable> void propagateIfInstanceOf( 102 @Nullable Throwable throwable, Class<X> declaredType) throws X { 103 if (throwable != null) { 104 throwIfInstanceOf(throwable, declaredType); 105 } 106 } 107 108 /** 109 * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage: 110 * 111 * <pre> 112 * for (Foo foo : foos) { 113 * try { 114 * foo.bar(); 115 * } catch (RuntimeException | Error t) { 116 * failure = t; 117 * } 118 * } 119 * if (failure != null) { 120 * throwIfUnchecked(failure); 121 * throw new AssertionError(failure); 122 * } 123 * </pre> 124 * 125 * @since 20.0 126 */ 127 public static void throwIfUnchecked(Throwable throwable) { 128 checkNotNull(throwable); 129 if (throwable instanceof RuntimeException) { 130 throw (RuntimeException) throwable; 131 } 132 if (throwable instanceof Error) { 133 throw (Error) throwable; 134 } 135 } 136 137 /** 138 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link 139 * RuntimeException} or {@link Error}. Example usage: 140 * 141 * <pre> 142 * try { 143 * someMethodThatCouldThrowAnything(); 144 * } catch (IKnowWhatToDoWithThisException e) { 145 * handle(e); 146 * } catch (Throwable t) { 147 * Throwables.propagateIfPossible(t); 148 * throw new RuntimeException("unexpected", t); 149 * } 150 * </pre> 151 * 152 * @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code 153 * null}. This method is scheduled to be removed in July 2018. 154 */ 155 @Deprecated 156 @GwtIncompatible 157 public static void propagateIfPossible(@Nullable Throwable throwable) { 158 if (throwable != null) { 159 throwIfUnchecked(throwable); 160 } 161 } 162 163 /** 164 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link 165 * RuntimeException}, {@link Error}, or {@code declaredType}. Example usage: 166 * 167 * <pre> 168 * try { 169 * someMethodThatCouldThrowAnything(); 170 * } catch (IKnowWhatToDoWithThisException e) { 171 * handle(e); 172 * } catch (Throwable t) { 173 * Throwables.propagateIfPossible(t, OtherException.class); 174 * throw new RuntimeException("unexpected", t); 175 * } 176 * </pre> 177 * 178 * @param throwable the Throwable to possibly propagate 179 * @param declaredType the single checked exception type declared by the calling method 180 */ 181 @GwtIncompatible // propagateIfInstanceOf 182 public static <X extends Throwable> void propagateIfPossible( 183 @Nullable Throwable throwable, Class<X> declaredType) throws X { 184 propagateIfInstanceOf(throwable, declaredType); 185 propagateIfPossible(throwable); 186 } 187 188 /** 189 * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link 190 * RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. In the 191 * unlikely case that you have three or more declared checked exception types, you can handle them 192 * all by invoking these methods repeatedly. See usage example in {@link 193 * #propagateIfPossible(Throwable, Class)}. 194 * 195 * @param throwable the Throwable to possibly propagate 196 * @param declaredType1 any checked exception type declared by the calling method 197 * @param declaredType2 any other checked exception type declared by the calling method 198 */ 199 @GwtIncompatible // propagateIfInstanceOf 200 public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible( 201 @Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) 202 throws X1, X2 { 203 checkNotNull(declaredType2); 204 propagateIfInstanceOf(throwable, declaredType1); 205 propagateIfPossible(throwable, declaredType2); 206 } 207 208 /** 209 * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link 210 * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates. 211 * 212 * <p>This method always throws an exception. The {@code RuntimeException} return type allows 213 * client code to signal to the compiler that statements after the call are unreachable. Example 214 * usage: 215 * 216 * <pre> 217 * T doSomething() { 218 * try { 219 * return someMethodThatCouldThrowAnything(); 220 * } catch (IKnowWhatToDoWithThisException e) { 221 * return handle(e); 222 * } catch (Throwable t) { 223 * throw Throwables.propagate(t); 224 * } 225 * } 226 * </pre> 227 * 228 * @param throwable the Throwable to propagate 229 * @return nothing will ever be returned; this return type is only for your convenience, as 230 * illustrated in the example above 231 * @deprecated Use {@code throw e} or {@code throw new RuntimeException(e)} directly, or use a 232 * combination of {@link #throwIfUnchecked} and {@code throw new RuntimeException(e)}. For 233 * background on the deprecation, read <a href="https://goo.gl/Ivn2kc">Why we deprecated 234 * {@code Throwables.propagate}</a>. This method is scheduled to be removed in July 2018. 235 */ 236 @CanIgnoreReturnValue 237 @GwtIncompatible 238 @Deprecated 239 public static RuntimeException propagate(Throwable throwable) { 240 throwIfUnchecked(throwable); 241 throw new RuntimeException(throwable); 242 } 243 244 /** 245 * Returns the innermost cause of {@code throwable}. The first throwable in a chain provides 246 * context from when the error or exception was initially detected. Example usage: 247 * 248 * <pre> 249 * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage()); 250 * </pre> 251 */ 252 public static Throwable getRootCause(Throwable throwable) { 253 Throwable cause; 254 while ((cause = throwable.getCause()) != null) { 255 throwable = cause; 256 } 257 return throwable; 258 } 259 260 /** 261 * Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code 262 * throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and 263 * will not reflect any subsequent changes to the cause chain. 264 * 265 * <p>Here's an example of how it can be used to find specific types of exceptions in the cause 266 * chain: 267 * 268 * <pre> 269 * Iterables.filter(Throwables.getCausalChain(e), IOException.class)); 270 * </pre> 271 * 272 * @param throwable the non-null {@code Throwable} to extract causes from 273 * @return an unmodifiable list containing the cause chain starting with {@code throwable} 274 */ 275 @Beta // TODO(kevinb): decide best return type 276 public static List<Throwable> getCausalChain(Throwable throwable) { 277 checkNotNull(throwable); 278 List<Throwable> causes = new ArrayList<Throwable>(4); 279 while (throwable != null) { 280 causes.add(throwable); 281 throwable = throwable.getCause(); 282 } 283 return Collections.unmodifiableList(causes); 284 } 285 286 /** 287 * Returns {@code throwable}'s cause, cast to {@code expectedCauseType}. 288 * 289 * <p>Prefer this method instead of manually casting an exception's cause. For example, {@code 290 * (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original 291 * exception {@code e} if the cause is not an {@link IOException}, but {@code 292 * Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link 293 * ClassCastException}'s cause. 294 * 295 * @throws ClassCastException if the cause cannot be cast to the expected type. The {@code 296 * ClassCastException}'s cause is {@code throwable}. 297 * @since 22.0 298 */ 299 @Beta 300 @GwtIncompatible // Class.cast(Object) 301 public static <X extends Throwable> X getCauseAs( 302 Throwable throwable, Class<X> expectedCauseType) { 303 try { 304 return expectedCauseType.cast(throwable.getCause()); 305 } catch (ClassCastException e) { 306 e.initCause(throwable); 307 throw e; 308 } 309 } 310 311 /** 312 * Returns a string containing the result of {@link Throwable#toString() toString()}, followed by 313 * the full, recursive stack trace of {@code throwable}. Note that you probably should not be 314 * parsing the resulting string; if you need programmatic access to the stack frames, you can call 315 * {@link Throwable#getStackTrace()}. 316 */ 317 @GwtIncompatible // java.io.PrintWriter, java.io.StringWriter 318 public static String getStackTraceAsString(Throwable throwable) { 319 StringWriter stringWriter = new StringWriter(); 320 throwable.printStackTrace(new PrintWriter(stringWriter)); 321 return stringWriter.toString(); 322 } 323 324 /** 325 * Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full 326 * trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in 327 * comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace() 328 * throwable.getStackTrace()}. Note, however, that this method's special implementation is not 329 * available for all platforms and configurations. If that implementation is unavailable, this 330 * method falls back to {@code getStackTrace}. Callers that require the special implementation can 331 * check its availability with {@link #lazyStackTraceIsLazy()}. 332 * 333 * <p>The expected (but not guaranteed) performance of the special implementation differs from 334 * {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly 335 * by delaying the per-stack-frame work until each element is accessed. Roughly speaking: 336 * 337 * <ul> 338 * <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to 339 * retrieve each element of the returned list. 340 * <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time 341 * to retrieve each element of the returned list (probably slightly more than {@code 342 * 1/stackSize}). 343 * </ul> 344 * 345 * <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace 346 * throwable.setStackTrace}. Instead, it always reflects the original stack trace from the 347 * exception's creation. 348 * 349 * @since 19.0 350 */ 351 // TODO(cpovirk): Say something about the possibility that List access could fail at runtime? 352 @Beta 353 @GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace 354 // TODO(cpovirk): Consider making this available under GWT (slow implementation only). 355 public static List<StackTraceElement> lazyStackTrace(Throwable throwable) { 356 return lazyStackTraceIsLazy() 357 ? jlaStackTrace(throwable) 358 : unmodifiableList(asList(throwable.getStackTrace())); 359 } 360 361 /** 362 * Returns whether {@link #lazyStackTrace} will use the special implementation described in its 363 * documentation. 364 * 365 * @since 19.0 366 */ 367 @Beta 368 @GwtIncompatible // getStackTraceElementMethod 369 public static boolean lazyStackTraceIsLazy() { 370 return getStackTraceElementMethod != null & getStackTraceDepthMethod != null; 371 } 372 373 @GwtIncompatible // invokeAccessibleNonThrowingMethod 374 private static List<StackTraceElement> jlaStackTrace(final Throwable t) { 375 checkNotNull(t); 376 /* 377 * TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks. 378 * 379 * TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause 380 * AOSP grief. 381 */ 382 return new AbstractList<StackTraceElement>() { 383 @Override 384 public StackTraceElement get(int n) { 385 return (StackTraceElement) 386 invokeAccessibleNonThrowingMethod(getStackTraceElementMethod, jla, t, n); 387 } 388 389 @Override 390 public int size() { 391 return (Integer) invokeAccessibleNonThrowingMethod(getStackTraceDepthMethod, jla, t); 392 } 393 }; 394 } 395 396 @GwtIncompatible // java.lang.reflect 397 private static Object invokeAccessibleNonThrowingMethod( 398 Method method, Object receiver, Object... params) { 399 try { 400 return method.invoke(receiver, params); 401 } catch (IllegalAccessException e) { 402 throw new RuntimeException(e); 403 } catch (InvocationTargetException e) { 404 throw propagate(e.getCause()); 405 } 406 } 407 408 /** JavaLangAccess class name to load using reflection */ 409 @GwtIncompatible // not used by GWT emulation 410 private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess"; 411 412 /** SharedSecrets class name to load using reflection */ 413 @GwtIncompatible // not used by GWT emulation 414 @VisibleForTesting 415 static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets"; 416 417 /** Access to some fancy internal JVM internals. */ 418 @GwtIncompatible // java.lang.reflect 419 @Nullable 420 private static final Object jla = getJLA(); 421 422 /** 423 * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to 424 * find it when available. When this is null, use the slow way. 425 */ 426 @GwtIncompatible // java.lang.reflect 427 @Nullable 428 private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod(); 429 430 /** 431 * The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it 432 * when available. When this is null, use the slow way. 433 */ 434 @GwtIncompatible // java.lang.reflect 435 @Nullable 436 private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(); 437 438 /** 439 * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not whitelisted for 440 * AppEngine, and not present in non-Sun JDKs. 441 */ 442 @GwtIncompatible // java.lang.reflect 443 @Nullable 444 private static Object getJLA() { 445 try { 446 /* 447 * We load sun.misc.* classes using reflection since Android doesn't support these classes and 448 * would result in compilation failure if we directly refer to these classes. 449 */ 450 Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null); 451 Method langAccess = sharedSecrets.getMethod("getJavaLangAccess"); 452 return langAccess.invoke(null); 453 } catch (ThreadDeath death) { 454 throw death; 455 } catch (Throwable t) { 456 /* 457 * This is not one of AppEngine's whitelisted classes, so even in Sun JDKs, this can fail with 458 * a NoClassDefFoundError. Other apps might deny access to sun.misc packages. 459 */ 460 return null; 461 } 462 } 463 464 /** 465 * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that 466 * method cannot be found (it is only to be found in fairly recent JDKs). 467 */ 468 @GwtIncompatible // java.lang.reflect 469 @Nullable 470 private static Method getGetMethod() { 471 return getJlaMethod("getStackTraceElement", Throwable.class, int.class); 472 } 473 474 /** 475 * Returns the Method that can be used to return the size of a stack, or null if that method 476 * cannot be found (it is only to be found in fairly recent JDKs). 477 */ 478 @GwtIncompatible // java.lang.reflect 479 @Nullable 480 private static Method getSizeMethod() { 481 return getJlaMethod("getStackTraceDepth", Throwable.class); 482 } 483 484 @GwtIncompatible // java.lang.reflect 485 @Nullable 486 private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath { 487 try { 488 return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes); 489 } catch (ThreadDeath death) { 490 throw death; 491 } catch (Throwable t) { 492 /* 493 * Either the JavaLangAccess class itself is not found, or the method is not supported on the 494 * JVM. 495 */ 496 return null; 497 } 498 } 499}