Google Guava学习(2)-Guava Preconditions类
来源:互联网 发布:晨枫网络是干嘛的 编辑:程序博客网 时间:2024/06/05 06:24
1. 功能:自定义异常信息
2. 代码:
package com.example.google.guava.demo.clazz;import com.google.common.base.Preconditions;/** * <p> * <code>PreconditionsTest</code> * </p> * Description:Preconditions提供静态方法来检查方法或构造函数,被调用是否给定适当的参数。它检查的先决条件。其方法失败抛出IllegalArgumentException。 * * @author Mcchu * @date 2017/10/18 16:21 */public class PreconditionsTest { public static void main(String[] args) { try { System.out.println(sqrt(-3.0)); }catch(IllegalArgumentException e){ System.out.println(e.getMessage()); } try { System.out.println(sum(null,3)); }catch(NullPointerException e){ System.out.println(e.getMessage()); } try { System.out.println(getValue(6)); }catch(IndexOutOfBoundsException e){ System.out.println(e.getMessage()); } try { System.out.println(overOne(0)); }catch (IllegalStateException e){ System.out.println(e.getMessage()); } } // 平方根 private static double sqrt(double input) throws IllegalArgumentException { Preconditions.checkArgument(input > 0.0, "异常信息:此参数不大于0,无法开平方根 %s.", input); return Math.sqrt(input); } // 求和 private static int sum(Integer a, Integer b){ a = Preconditions.checkNotNull(a, "异常信息:第一个参数为null."); b = Preconditions.checkNotNull(b, "异常信息:第二个参数为null."); return a+b; } // 判断数组长度 private static int getValue(int input){ int[] data = {1,2,3,4,5}; Preconditions.checkElementIndex(input,data.length, "异常信息:数组长度越界."); return 0; } // 判断状态 private static int overOne(int input){ Preconditions.checkState( input>1, "异常信息:传入数据不大于1" ); return 0; }}3. 输出:
异常信息:此参数不大于0,无法开平方根 -3.0.异常信息:第一个参数为null.异常信息:数组长度越界. (6) must be less than size (5)异常信息:传入数据不大于1
附录:
参考:http://www.yiibai.com/guava/guava_preconditions_class.html
阅读全文
0 0
- Google Guava学习(2)-Guava Preconditions类
- Guava Preconditions类使用【Guava学习笔记】
- google guava Preconditions
- Guava学习之Preconditions
- google guava的Preconditions使用
- guava-Preconditions
- Guava学习之旅 - Preconditions
- Google Guava学习(1)-Guava Optional类
- Google Guava学习(3)-Guava Ordering类
- Google Guava学习(4)-Guava Range类
- Google Guava学习(5)-Guava Throwables类
- [Guava源码日报](4)Preconditions
- Guava之Preconditions
- Guava — Preconditions
- Guava base -- Preconditions
- Guava使用之Preconditions
- Guava学习笔记:Google Guava 类库简介
- Guava学习笔记:Google Guava 类库简介
- 【干货分享】大数据计算服务MaxCompute使用教程
- JS与JQUERY的区别
- Spring DAO层设计思想
- tlb与dll文件区别
- Qt对话框图片Debug下可显示,release下不可显示的解决办法
- Google Guava学习(2)-Guava Preconditions类
- 客户信息管理系统1--前期准备
- 2006年培养学员8万人,每年增长25%,请问按照次增长速度,到哪一年培养学员人数将达到20万人?(分别用while do while 和 for语句作答)
- 常用 vim/终端 命令-----笔记
- 数据结构与算法Java版——中缀表达式转后缀表达式
- Android开发知识(九):Android事件处理机制:事件分发、传递、拦截、处理机制的原理分析(下)
- WIN编程书籍总结
- opencv 16 OCR 端到端场景文本检测与识别(webcam_demo) vs2015
- FastJson基本用法