I am writing some Java code and am coming across a try/catch block in which I decided to verify the value is not null
before parsing it:
String parsedValue = DEFAULT_VALUE;
try {
if (myValue != null) {
parsedValue = parse(myValue);
}
} catch (ParseException e) {
log(e);
}
Regarding the code above, my question is, is it better to nest the if
loop into the try/catch
block or vice-versa?
In other words, is the previous code better or the following:
String parsedValue = DEFAULT_VALUE;
if (myValue != null) {
try {
parsedValue = parse(myValue);
} catch (ParseException e) {
log(e);
}
}
EDIT: As @Brythan raised the issue, for simplicity, let's assume here that log
is a method in a random logging library, and has the 2 signatures log(Exception)
and log(String)
. Like that we avoid creating an Exception to log a message, it makes the code clearer.
As @h.j.k raised another issue, here myValue
could be null
, this is no exceptional case, but if myValue
has been assigned a value (not null
), it should be parseable, and only in that case I expect an Exception to be thrown by parse(String)
.
myValue
is null,parsedValue
will have the valueDEFAULT_VALUE
. \$\endgroup\$