In the section When to Use Exception in The Pragmatic Programmer, the book writes that instead of:
retcode = OK;
if (socket.read(name) != OK) {
retcode = BAD_READ;
}
else {
processName(name);
if (socket.read(address) != OK) {
retcode = BAD_READ;
}
else {
processAddress(address);
if (socket.read(telNo) != OK) {
retcode = BAD_READ;
}
else {
// etc, etc...
}
}
}
return retcode;
, they prefer:
retcode = OK;
try {
socket.read(name);
process(name);
socket.read(address);
processAddress(address);
socket.read(telNo);
// etc, etc...
}
catch (IOException e) {
retcode = BAD_READ;
Logger.log( "Error reading individual: " + e.getMessage());
}
return retcode;
simply because it looks neater. I'm all for neater code, however isn't unnecessary catching of Exceptions a performance bottleneck?
I can understand that we should give up minuscule optimization for neater code (at least 99% of the times), however from what I know, catching exceptions belong to the class of code which have a noticeable delay in runtime. Hence I was wondering what's the justification that the second piece of code is preferred over the first code?
Or rather, which code would you prefer?