Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 643
Adrián Pérez Avatar asked Sep 13 '13 10:09

Adrián Pérez


People also ask

Should you use try catch in Java?

Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Are try catches expensive Java?

try has almost no expense at all. Instead of doing the work of setting up the try at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any try blocks exist that would catch this exception.

Should you use try catch blocks?

Like some others have said, you want to use try-catch blocks around code that can throw an Exception AND code that you are prepared to deal with. Regarding your particular examples, File. Delete can throw a number of exceptions, for example, IOException , UnauthorizedAccessException .

How does try catch affect performance?

In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.

What is the use of try catch in Java?

The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of the program. Here's the syntax of a try...catch block in Java. try{ // code } catch(exception) { // code } The try block includes the code that might generate an exception.

What is the difference between try block and catch block in Java?

A try block must be followed by catch blocks or finally block or both. A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try

How to catch more than one type of exception in Java?

From Java SE 7 and later, we can now catch more than one type of exception with one catch block. This reduces code duplication and increases code simplicity and efficiency. Each exception type that can be handled by the catch block is separated using a vertical bar |.

When does the catch block get executed in Java?

The catch block is only executed if there exists an exception inside the try block. Note: In Java, we can use a try block without a catch block. However, we cannot use a catch block without a try block.


3 Answers

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.

like image 62
Bartosz Bilicki Avatar answered Oct 08 '22 09:10

Bartosz Bilicki


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.

like image 35
OldCurmudgeon Avatar answered Oct 08 '22 08:10

OldCurmudgeon


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.

like image 14
dharam Avatar answered Oct 08 '22 08:10

dharam