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