public final class Throwables extends Object
Static utility methods pertaining to instances of
Throwable.static List<Throwable> | getCausalChain(Throwable throwable)Gets a Throwable cause chain as a list. |
static Throwable | getRootCause(Throwable throwable)Returns the innermost cause of throwable. |
static String | getStackTraceAsString(Throwable throwable)Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable. |
static RuntimeException | propagate(Throwable throwable)Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException then propagates. |
static <X extends Throwable> | propagateIfInstanceOf(Throwable throwable, Class<X> declaredType)Propagates throwable exactly as-is, if and only if it is an instance of declaredType. |
static void | propagateIfPossible(Throwable throwable)Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException or Error. |
static <X extends Throwable> | propagateIfPossible(Throwable throwable, Class<X> declaredType)Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, or declaredType. |
static <X1 extends Throwable,X2 extends Throwable> | propagateIfPossible(Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, declaredType1, or declaredType2. |
/**
*
*/
package com.rajkrrsingh.test.guava;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Throwables;
/**
* @author rks
* @04-Jan-2015
*/
public class GuavaBiMapAndMultiMapDemo {
public static void main(String[] args) throws Exception {
throwablesDemo();
}
// working with throwables
public static void throwablesDemo() throws Exception {
try {
try {
try {
throw new RuntimeException("Root exception");
}
catch(Exception e) {
throw new SQLException("Middle tier exception", e);
}
}
catch(Exception e) {
throw new IllegalStateException("outer exception", e);
}
}
catch(Exception e) {
// getting the root exception
System.out.println(Throwables.getRootCause(e).getMessage());
// list of exceptions
List<Throwable> list = Throwables.getCausalChain(e);
Iterator<Throwable> itr= list.iterator();
while(itr.hasNext()){
System.out.println(itr.next().getMessage());
}
// get stacktrace as string
System.out.println(Throwables.getStackTraceAsString(e));
}
}
}
No comments:
Post a Comment