(笔记)异常处理:try/catch的应用例子(finally待整理)

4 篇文章 0 订阅
2 篇文章 0 订阅

题目:判断传入的字符串是否为ip地址

     /**
	 * 判断传入的字符串是否为ip地址
	 * @param ip
	 * @return
	 * @throws Exception
	 */
	public static boolean isIP(String ip) throws Exception {
		boolean isTrue=false;
		ip = ip.replace(" ", "");//去除空格
		
		String[] arr=ip.split("\\.");//根据“.”将字符串分割
		if(arr.length==4) {
			for (int i = 0; i < 4; i++) {
				if(isInt(arr[i])==false) {
					throw new Exception("【"+ip+"】"+"第"+(i+1)+"个部分不是数字");
				}
				int temNum=toInt(arr[i]);
				if(temNum>255||temNum<0) {
					throw new Exception("【"+ip+"】"+"第"+(i+1)+"个部分数字超出范围") ;
				}
			}
			isTrue=true;
		}else {
			throw new Exception("【"+ip+"】不是四个区段,应该形如127.0.0.1");
		}	
		return isTrue;
	}


    /**
	 * 判断字符串是否为纯数字(int类型),返回布尔类型值
	 * @param pstr
	 * @return
	 */
	public static boolean isInt(String pstr){
		boolean isOk=false;
		try {
			int tem=Integer.parseInt(pstr);
			isOk=true;
		}catch(Exception e){
			
		}
		return isOk;
	}


     /**
	 * 转换字符串为纯数字(int类型),返回转换后的数字
	 * 异常则返回数字0
	 * @param pstr
	 * @return
	 */
	public static int toInt(String pstr){
		int tem;
		try {
			tem=Integer.parseInt(pstr);
		}catch(Exception e){
			tem=0;
		}
		return tem;
	}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值