Better handling of number format exception in android

 ̄綄美尐妖づ 提交于 2021-02-10 13:26:10

问题


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

回答1:


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
}


来源:https://stackoverflow.com/questions/8125163/better-handling-of-number-format-exception-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!