更好地处理android中的数字格式异常

时间:2011-11-14 16:59:51

标签: java android validation exception-handling

我有以下代码片段,我正在考虑重构一个更抽象的应用程序异常处理程序,但我想确保我已经尽可能整洁了

有关如何改进此代码或使其更具可恢复性的任何建议

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.
}

1 个答案:

答案 0 :(得分:4)

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

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