更好地处理Android中的数字格式异常 [英] Better handling of number format exception in android

查看:47
本文介绍了更好地处理Android中的数字格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段,我正在考虑将其重构为更抽象的应用程序异常处理程序,但我想确保首先使它尽可能整洁

I've got the following code snippet that I'm thinking of refactoring to a more abstract application exception handler but I want to make sure I've got it as tidy as possible first

有关如何改进此代码或使其更易于使用的任何建议

Any suggestions on how to improve this code or make it more resuable

int id = -1;
final StringBuilder errorMessage = new StringBuilder("Bad Input Value: ");
try {
        id = Integer.parseInt(edtId.getText().toString());
} catch (final NumberFormatException e) {
        errorMessage.append("Failed to parse id " + e.getMessage());
}

if (id < 0) {
    errorToast(errorMessage.toString());
} else {
    //go ahead an retreive values from database knowing the id has been parsed
    //correctly to a positive int.
}

推荐答案

为什么将ID预先分配给幻数?

Why pre-assign id to a magic number?

try {
    int id=Integer.parseInt(edtId.getText().toString());
    //go on as normal
} catch (NumberFormatException e) {
    //handle error
}

这篇关于更好地处理Android中的数字格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆