有时候, 当我们我们捕获异常, 并且像把这个异常传递到下一个try/catch块中。guava提供了一个异常处理工具类, 可以简单地捕获和重新抛出多个异常。
[code]import java.io.ioexception;
import org.junit.test;
import com.google.common.base.throwables;
public class throwablestest {
@test
public void testthrowables(){
try {
throw new exception();
} catch (throwable t) {
string ss = throwables.getstacktraceasstring(t);
system.out.println("ss:"+ss);
throwables.propagate(t);
}
}
@test
public void call() throws ioexception {
try {
throw new ioexception();
} catch (throwable t) {
throwables.propagateifinstanceof(t, ioexception.class);
throw throwables.propagate(t);
}
}
}
将检查异常转换成未检查异常,例如:
[code]import java.io.inputstream;
import java.net.url;
import org.junit.test;
import com.google.common.base.throwables;
public class throwablestest {
@test
public void testcheckexception(){
try {
url url = new url("http://ociweb.com");
final inputstream in = url.openstream();
// read from the input stream
in.close();
} catch (throwable t) {
throw throwables.propagate(t);
}
}
}
传递异常的常用方法:
1.runtimeexception propagate(throwable):把throwable包装成runtimeexception,用该方法保证异常传递,抛出一个runtimeexception异常
2.void propagateifinstanceof(throwable, class) throws x:当且仅当它是一个x的实例时,传递throwable
3.void propagateifpossible(throwable):当且仅当它是一个runtimeexception和error时,传递throwable
4.void propagateifpossible(throwable, class) throws x:当且仅当它是一个runtimeexception和error时,或者是一个x的实例时,传递throwable。
[code]import java.io.ioexception;
import org.junit.test;
import com.google.common.base.throwables;
public class throwablestest {
@test
public void testthrowables(){
try {
throw new exception();
} catch (throwable t) {
string ss = throwables.getstacktraceasstring(t);
system.out.println("ss:"+ss);
throwables.propagate(t);
}
}
@test
public void call() throws ioexception {
try {
throw new ioexception();
} catch (throwable t) {
throwables.propagateifinstanceof(t, ioexception.class);
throw throwables.propagate(t);
}
}
public void testpropagateifpossible() throws exception {
try {
throw new exception();
} catch (throwable t) {
throwables.propagateifpossible(t, exception.class);
throwables.propagate(t);
}
return null;
}
}
guava的异常链处理方法:
1.throwable getrootcause(throwable)
2.list getcausalchain(throwable)
3.string getstacktraceasstring(throwable)
以上就是java-类库-guava-throwables类的内容。