Is it a known good practice to use a big try-catch per method in java?

JavaExceptionTry Catch

Java Problem Overview


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.

Java Solutions


Solution 1 - 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 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.

Solution 2 - Java

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.

Solution 3 - Java

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 (https://stackoverflow.com/questions/10169671/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.

Solution 4 - Java

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)

Solution 5 - Java

As for me, it's clearer to have just one try-catch block wrapping all the 'hazardous' code in a method. Regarding who to blame when two lines throw the same exception, you'll always have the stacktrace.

Besides, having more than one try-catch inside a method usually means having more than one return lines (which can also make hard to follow code execution at a sight), as chances are that if something goes wrong in the first try-catch, it won't make sense to keep running the rest of the code.

Here you can find some 'standard' best practices, just in case you may find them useful.-

http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/

Solution 6 - Java

This is another thing that often starts Java-flamewar... ;-)

Basically, for the performance matters only throwing exceptions. So using few try-catch blocks shouldn't affect a performance at all. In some opinion writing code that way obfuscates the code and does not even recall "clean code", in others opinion it's better to use try only for lines which can actually throw any exception.

It's up to you decide (or the team convention).

Solution 7 - Java

It's also important to consider the context of the code. If you're writing code with heavy IO then you may need to know which parts of the code are failing. I didn't see anywhere yet a point that try...catch is meant to give you a chance to recover from a problem.

So if you get an IO exception in reading from one file, you may want to retry reading. Same with writing. But if you had one large try...catch you wouldn't know which to retry.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdri&#225;n P&#233;rezView Question on Stackoverflow
Solution 1 - JavaBartosz BilickiView Answer on Stackoverflow
Solution 2 - JavaOldCurmudgeonView Answer on Stackoverflow
Solution 3 - JavadharamView Answer on Stackoverflow
Solution 4 - JavaTom AndersonView Answer on Stackoverflow
Solution 5 - JavassantosView Answer on Stackoverflow
Solution 6 - JavaEel LeeView Answer on Stackoverflow
Solution 7 - JavaCLoView Answer on Stackoverflow