'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.



Solution 1:[1]

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 2:[2]

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.

Solution 3:[3]

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 4:[4]

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 5:[5]

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 6:[6]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OldCurmudgeon
Solution 2 Community
Solution 3 Tom Anderson
Solution 4
Solution 5 Eel Lee
Solution 6 CLo