我有以下代码 fragment ,我正在考虑将其重构为更抽象的应用程序异常处理程序,但我想首先确保它尽可能整洁
有关如何改进此代码或使其更可重用的任何建议
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 预先分配给魔数(Magic Number)?
try {
int id=Integer.parseInt(edtId.getText().toString());
//go on as normal
} catch (NumberFormatException e) {
//handle error
}
关于java - 更好地处理android中的数字格式异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125163/