java面试题网

普通会员

483

帖子

9

回复

187

积分

楼主
发表于 2019-08-26 15:24:39 | 查看: 5047| 回复: 0

Guava Throwable类

Guava Throwable类

Throwable类提供了相关的Throwable接口的实用方法。

类声明

以下是com.google.common.base.Throwables类的声明:

public final class Throwables
   extends Object

类方法

Guava Throwable类_www.wityx.com

继承的方法

这个类继承了以下类方法:

java.lang.Object

Throwables示例

创建使用所选择的任何编辑器下面的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)

 


文章来自www.wityx.com,转载请注明出处!原文地址http://www.wityx.com/post/1250_1_1.html


java面试题交流群:327440556

上一篇:Guava集合工具 下一篇:Guava Range类
您需要登录后才可以回帖 登录 | 立即注册

java面试题网www.wuliaokankan.cnjava建站系统提供技术支持V2.1 网站地图 © 2016-2018