我想知道处理NumberFormatException
的最佳方法是什么?处理NumberFormatExeption的最佳做法
A NumberFormatException
每当用户传递一个空字符串时,都会在我的代码中被抛出。有多种方法可以处理这个问题,但我不确定最佳方法是什么?
这里是我的代码是现在:
if(result != null) {
String [] values = result.trim().split(",");
// This is where the NumberFormatException occurs
long docId = Long.parseLong(values[0]);
//There is more to the code but the rest is unnecessary :)
break;
}
我应该避免NumberFormatException的一起通过检查values[0]
是在解析之前是空的?所以这样的事情:
if(result!= null) {
String [] values = result.trim().split(",");
if("".equals(values[0]) {
// This method returns void hence the empty return statement.
return;
}
long docId = Long.parseLong(values[0]);
break;
}
或者我应该捕捉异常,如果它发生?
if(result!= null) {
String [] values = result.trim().split(",");
try{
long docId = Long.parseLong(values[0]);
} catch (NumberFormatExeption e) {
LOGGER.warn("Exception in ThisClass :: ", e);
return;
}
break;
}
或者还有另一种方法,你推荐?
也许这是类似的:http://stackoverflow.com/questions/4410107/what-is-the-proper-way-to-handle-a-numberformatexception-when-it-is-expected –
这不是一个重复!我正在寻求最佳做法。请重新打开@TimBiegeleisen这个问题。 – robben
同意。这个问题不是那个问题的重复。 –