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?
Using catching exceptions to improve readability, Good or Bad?
java;exception handling;language agnostic
Exceptions are typically only slower if they actually thrown. Usually, the exceptions in situations like this are rare so its not something you should worry about. You should only really worry about the performance of exceptions if they are happening all the time and thus are a significant factor.The second code is better because its much easier to follow the logic. The error handling is nicely localised. The only objection is that if you are using exceptions, then use exceptions. Don't catch the exceptions and then return an error code.