Throwable類提供了相關的Throwable接口的實用方法。
以下是com.google.common.base.Throwables類的聲明:
public final class Throwables
? ?extends Object
類方法
繼承的方法
這個類繼承了以下類方法:java.lang.Object
創建使用所選擇的任何編輯器下面的java程序,比如 C:/> Guava
GuavaTester.java
import java.io.IOException;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
public class GuavaTester {
public static void main(String args[]){
GuavaTester tester = new GuavaTester();
try {
tester.showcaseThrowables();
} catch (InvalidInputException e) {
//get the root cause
System.out.println(Throwables.getRootCause(e));
}catch (Exception e) {
//get the stack trace in string format
System.out.println(Throwables.getStackTraceAsString(e));
}
try {
tester.showcaseThrowables1();
}catch (Exception e) {
System.out.println(Throwables.getStackTraceAsString(e));
}
}
public void showcaseThrowables() throws InvalidInputException{
try {
sqrt(-3.0);
} catch (Throwable e) {
//check the type of exception and throw it
Throwables.propagateIfInstanceOf(e, InvalidInputException.class);
Throwables.propagate(e);
}
}
public void showcaseThrowables1(){
try {
int[] data = {1,2,3};
getValue(data, 4);
} catch (Throwable e) {
Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);
Throwables.propagate(e);
}
}
public double sqrt(double input) throws InvalidInputException{
if(input < 0) throw new InvalidInputException();
return Math.sqrt(input);
}
public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
return list[index];
}
public void dummyIO() throws IOException {
throw new IOException();
}
}
class InvalidInputException extends Exception {
}
驗證結果
使用javac編譯器編譯如下類
C:\Guava>javac GuavaTester.java
現在運行GuavaTester看到的結果
C:\Guava>java GuavaTester
看到結果
InvalidInputException
java.lang.ArrayIndexOutOfBoundsException: 4
?? ?at GuavaTester.getValue(GuavaTester.java:52)
?? ?at GuavaTester.showcaseThrowables1(GuavaTester.java:38)
?? ?at GuavaTester.main(GuavaTester.java:19)
?
轉載自并發編程網-ifeve.com