灵活的使用try catch

     最近在使用一些第三方控件的时候,他需要我时间进去,但是是把"2017-08-14 18:22:19"这样的时间格式拆分,比如下面这样:

selectedDate.set(Integer.valueOf(time.substring(0, 4)), Integer.valueOf(time.substring(5, 7)) - 1
                        , Integer.valueOf(time.substring(8, 10)), Integer.valueOf(time.substring(11, 13))
                        , Integer.valueOf(time.substring(14, 16)), Integer.valueOf(time.substring(17, 19)));
才可以使用他的控件,,,可是这个time不是我来控制的,是web端从excel导入的,如果服务器没有做相当仔细的判断,那么传给我的数据有可能是下面举例的这几种情况:"2017-08-14 18:62:30","2017-08-14 18:22:30  ","2017-08-14-18:22:30","2017-08-0418:22:30",我裁剪之后,控件就蹦了。。。。这个控件没有做try catch,所以,,我自己就在他外面的自己写了一个try catch,而且像这种情况客户端只能识别数据完整性,并不能对数据进行非用户操作的修改。所以直接try catch,只要格式不对就提示用户如下:
 try {
            if (selectedDate != null)
                selectedDate.set(Integer.valueOf(time.substring(0, 4)), Integer.valueOf(time.substring(5, 7)) - 1
                        , Integer.valueOf(time.substring(8, 10)), Integer.valueOf(time.substring(11, 13))
                        , Integer.valueOf(time.substring(14, 16)), Integer.valueOf(time.substring(17, 19)));
        } catch (Exception e) {
            time = TimeFormartUtils.getCurrentTimeSeconds();
            if (selectedDate != null) {
                ToastUtils.showToast("服务器端时间格式不对,不支持进行时间选择,只能暂时用系统时间替代");
                selectedDate.set(Integer.valueOf(time.substring(0, 4)), Integer.valueOf(time.substring(5, 7)) - 1
                        , Integer.valueOf(time.substring(8, 10)), Integer.valueOf(time.substring(11, 13))
                        , Integer.valueOf(time.substring(14, 16)), Integer.valueOf(time.substring(17, 19)));
            } else {
                ToastUtils.showToast("控件出现问题,暂时无法选择时间");
            }
        }

,这样使用try catch就可以处理自己无法控制的异常,并保证客户端的稳定性。其实这种使用思想可以直接推广到其他代码使用。谢谢

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值