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.
Advertisement
Answer
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.