Is it a known good practice to use a big try-catch per method in java? [closed]
I've been interviewed recently and the interviewer wanted me to do a technical test to see my knowledge. After I finished it he gave me feedback about how I did it, which I didn't expect and I appreciated, since few interviewers do it if they don't want to hire you.
One of the things he told me that he saw bad about my code was that I used more than one try-catch block inside each method I wrote. This calls my attention since I see it interesting.
I believe at the moment that I should make try-catch blocks where there is a semantically distinguishable block of code which has one or more methods that can throw exceptions needed to be caught. The only exception to this that I followed was that if two methods throw the same exception type, I better put them in different try-catch blocks to clearly distinguish when debugging where and why an exception was thrown.
This strongly differs from what the interviewer wanted me to do. So is using just one try-catch block per method a known good practice? If it is a known good practice what are the benefits of doing it?
Please note that I would like to know if this is a known good practice. I.e. if most programmers/authors would agree that this is a good practice.
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 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.
I try to avoid duplication in catch blocks. If all the exceptions in a method receive the same treatment in the catch block, then go ahead and catch them all together. If you need to do different things with them, then catch them separately.
For example, here we can catch all exceptions together, because any kind of exception means the whole method fails:
public PasswordAuthentication readAuthenticationDetails(File authenticationFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(authenticationFile));
String username = reader.readLine();
String password = reader.readLine();
return new PasswordAuthentication(username, password.toCharArray());
} catch (IOException e) {
return null;
}
}
Whereas here, we have different fallback behaviour for each group of calls, so we catch separately:
public Collection<String> readServerHostnames(File mainServerConfigFile, File backupServerConfigFile) {
String mainServerHostname;
try {
BufferedReader reader = new BufferedReader(new FileReader(mainServerConfigFile));
mainServerHostname = reader.readLine();
} catch (IOException e) {
mainServerHostname = "default-server.example.org";
}
String backupServerHostname;
try {
BufferedReader reader = new BufferedReader(new FileReader(backupServerConfigFile));
backupServerHostname = reader.readLine();
} catch (IOException e) {
backupServerHostname = "default-server.example.ru";
}
return Arrays.asList(mainServerHostname, backupServerHostname);
}
(This code exists purely to illustrate this point about catching exceptions; i beg you to disregard the fact that it is utterly horrible in other ways)