Is it good practice to use a large try-catch method for each method in java?

I was recently interviewed and the interviewer wanted me to do a technical test to see my knowledge. After I finished, he gave me feedback on how I did this, which I did not expect, and I appreciated this, as several interviewers do this if they do not want to hire you.

One of the things that he told me that he didn’t see my code well was that I used more than one try-catch block inside each method that I wrote. It attracts my attention, as I see it interesting.

I believe that at the moment I should create try-catch blocks where there is a semantically distinguishable block of code that has one or more methods that can throw exceptions that need to be caught. The only exception to this that I followed was that if two methods use the same type of exception, I would rather put them in different try-catch blocks to clearly distinguish when debugging where and why the exception was thrown.

This is very different from what the interviewer wanted to do. Thus, only one try-catch block is used for each method - is it a known good practice? If this is good practice, what are the benefits of this?

EDIT: I really appreciate your thoughts on this, it's very good. Although note that I'm asking if this is a known good practice. This is if most programmers agree to this, and it is written as good practice in some book

+50
java exception-handling try-catch
Sep 13 '13 at 10:52 on
source share
7 answers

For me, two try-catch blocks make most methods too long. It confuses intention if a method does a lot of things.

With two try-catch blocks, it does at least four things, to be precise

  • two cases for the main thread (two try blocks)
  • two cases for error handling (blocking blocks)

I would prefer to make short and clear methods from each try-catch block.

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 him to the next level, proposing:

if the "try" keyword exists in the 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 a method with two separate try / catch blocks into smaller methods.

+29
Sep 13 '13 at 20:48
source share

I would say that if you find yourself wrapping two separate blocks of code with try/catch , you should consider reorganizing these blocks into separate methods. If this is the sample you used in your interview, you may have misunderstood your interviewer.

It is perfectly normal to use two try/catch blocks if this requires an algorithm. I often used a new try/catch in a catch block to provide a safe cleanup, so a close statement is not possible.

+27
Sep 13 '13 at 11:00
source share

To answer your question, when we talk about modern JVMs that actually apply a lot of optimizations in the code, when you write some code that is inefficient, the JVM automatically introduces optimization.

Please answer the answer in ( Java: the overhead of entering / using try-catch blocks?).

Therefore, good practice is not a big deal.

In a personal note, I believe that there is no need to encapsulate anything in try-catch , static , synchronized , etc. blocks are optional.

Let's make our code more understandable for those who will work on this. If an exception is caught, it is better to explicitly indicate which part of the code throws it.

Lack of guessing for the reader, so the JVMs are smart, write according to your wishes, make them better for people, and the JVM takes care of the optimization part.

EDIT: I read a lot of books, and I did not find a single place that says that one big attempt to catch is better than a few small ones.

In addition, many in the development community believe the opposite.

+13
Sep 13 '13 at 11:01
source share

I try to avoid duplication in catch blocks. If all exceptions in the 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 combine all exceptions, because any exception means that the whole method is not executed:

 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; } } 

While here we have different rollback behavior 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 to illustrate this point about throwing an exception, I ask you to ignore the fact that it is completely terrible in other ways)

+8
Sep 13 '13 at 17:19
source share

As for me, it will be clearer to have only one try-catch that wraps all the “dangerous” code in the method. As for who is to blame when two lines throw the same exception, you will always have a stack.

In addition, the presence of more than one try-catch inside a method usually means the presence of more than one return line (which can also complicate code execution when viewing), since it is likely that if something goes wrong in the first try-catch , then it will make sense to continue working with the rest of the code.

Here you can find some “standard” best practices, in case you find them useful.

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

+6
Sep 13 '13 at 11:02
source share

It is also important to consider the context of the code. If you are writing code with a heavy IO, you may need to know which parts of the code fail. I have never seen a point trying ... catch is intended to give you the opportunity to recover from a problem.

So, if you get an IO exception when reading from a single file, you might want to repeat the reading. The same thing with the letter. But if you had one big attempt ... to catch, you do not know what needs to be repeated.

+5
Sep 13 '13 at 16:01
source share

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

In principle, for performance it is important to exclude only exceptions. Therefore, using multiple try-catch blocks should not affect performance at all. In some opinion, writing code in this way confuses the code and does not even remember “clean code”; in other cases, it is better to use try only for strings that can actually raise any exception.

It's up to you (or team agreement).

+4
Sep 13 '13 at 10:58 on
source share



All Articles