有時候, 當我們我們捕獲異常, 並且像把這個異常傳遞到下一個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):把throwableceptionRuntimeException,用該方法保證一個異常傳遞異常值的異常
2.void propagateIfInstanceOf(Throwable, Class) throws X:當且僅當它是一個X的實例時,傳遞throwable
3.void propaic prodid propaic(Thwulwulwulwulwulwulwet Nelisconpaodid propaidable(Thr. ,傳遞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)以上就是Java-類別庫-Guava-Throwables類的內容,更多相關內容請關注PHP中文網(www.php.cn)!