I want to know what is the best way to handle a NumberFormatException
?
A NumberFormatException
gets thrown in my code whenever a user passes an empty string. There are multiple of ways to handle this but I am not sure what the best approach is?
Here is my code as is now:
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;
}
Should I just avoid the NumberFormatException all together by checking if values[0]
is empty before parsing? So something like this:
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;
}
Or should I catch the exception if it occurs?
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;
}
Or is there another approach you recommend?