I usually like to declare my local variables as final but I see repeating patterns where I cannot do this when I have to handle an exception during its initialization.
For ex I have this code:
final Client myClient = library.getClient("service");
//do a bunch of steps with myClient
But I end up modifying it very often like this:
Client myClient = null;
try {
myClient = library.getClient("service");
} catch (someException ex) {
// handle
throw ex;
}
// do stuff with myClient
I do not want to add the catch after I do all the stuff as it becomes a bit unreadable as it is towards the end. So is there a better way to do this?
You can put the try/catch in a separate method:
If it doesn’t make sense for the processing to continue in the method that calls
getClient(), then the other option is to declare it to throw the exception and get rid of the try/catch block.