Is it a known good practice to use a big try-catch per method in java?
For me, two try-catch blocks makes most methods too long. It obfuscates the intention if the method is doing many things.
With two try-catch blocks, it's doing at least four things, to be precise
- two cases for main flow (two try blocks)
- two cases for error handling (catch blocks)
I would rather make short and clear methods out of each try-catch block- like
private String getHostNameFromConfigFile(String configFile, String defaultHostName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(configFile));
return reader.readLine();
} catch (IOException e) {
return defaultHostName;
}
}
public Collection<String> readServerHostnames(File mainServerConfigFile, File backupServerConfigFile) {
String mainServerHostname=getHostNameFromConfigFile(mainServerConfigFile,"default- server.example.org");
String backupServerHostName=getHostNameFromConfigFile(backupServerConfigFile,"default- server.example.ru")
return Arrays.asList(mainServerHostname,backupServerHostName);
}
Robert C. Martin in 'Clean Code' takes it to next level, suggesting:
if the keyword 'try' exists in a function, it should be the very first word in the function and that there should be nothing after the catch/finally blocks.
I would definitely refactor the method with two separate try/catch blocks into smaller methods.
I'd say that if you find yourself wrapping two separate blocks of code with try/catch
you should consider refactoring those blocks into separate methods. If this is a pattern you used in your interview than perhaps you misunderstood your interviewer.
It is perfectly fine to use two try/catch
blocks if the algorithm requires it. I have often used a new try/catch
in a catch block to ensure a safe cleanup so a blanket statement is not possible.
To answer your question, when we talk about modern day JVMs which are actually applying a lot of optimizations in the code, when you write some code which is inefficient then the JVM will automatically introduce optimizations.
Please refer the answer in (Java: overhead of entering/using "try-catch" blocks?).
So the good practice thing is not of much importance.
On a personal note, I believe that one must not encapsulate anything in a try-catch
, static
, synchronized
etc blocks un-necessarily.
Let us make our code more readable to the ones who will be working on this. If an exception is caught, it is better to explicitly make it prominent that which piece of code is throwing it.
No guessing for the reader, that is why JVMs are smart, write as you want , make it better for humans and JVM takes care of the optimization part.
EDIT: I have read plenty of books and I didn't find it any place which says that one big try catch is better than multiple small ones.
Moreover, many in the developer community believe the opposite.