Guava學習筆記:簡化異常處理的Throwables類

  有時候, 當咱們咱們捕獲異常, 而且像把這個異常傳遞到下一個try/catch塊中。Guava提供了一個異常處理工具類, 能夠簡單地捕獲和從新拋出多個異常。例如:java

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);
        }
    }    
}

   將檢查異常轉換成未檢查異常,例如:web

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<X extends Exception>) throws X:當且僅當它是一個X的實例時,傳遞throwable
  3.void propagateIfPossible(Throwable):當且僅當它是一個RuntimeException和Error時,傳遞throwable
   4.void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X:當且僅當它是一個RuntimeException和Error時,或者是一個X的實例時,傳遞throwable。google

  使用實例:url

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的異常鏈處理方法:.net

  1.Throwable getRootCause(Throwable)
  2.List<Throwable> getCausalChain(Throwable)
  3.String getStackTraceAsString(Throwable)code

相關文章
相關標籤/搜索