4

This might be a weird question, but I still thought I would ask to get insights into this, and stop me from doing something wrong while I am coding.

Let's say I have a function func1(), inside which I call a function func2(). func2() throws an exception e1. And I want to catch this exception inside func1().

So does it matter whether I start a try block at the beginning of the function itself and end it at the end of func1() with the catch block, rather than just surrounding the part of the code where I call function func2().

I know from the coders perspective, where if an exception is thrown, he will be able to know exactly where the exception came from. If we ignore this, are there any other ill effects of just placing the whole method inside try-catch?

Edit - Code Fragment

So I am converting a JSON String to JSON Node. This operation throws an exception. But instead of surrounding this one statement with a try-catch block, I put the whole function inside the try block. It just looks cleaner to me. :)

public void storePublicData(String publicData, String twitterId) {

    try {

        Date date=new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String day = formatter.format(date);

        BasicDBObject query = new BasicDBObject("date", day);
        query.append("brand_id", twitterId);

        JsonNode publicDataJsonNode;

        publicDataJsonNode = JSONOperations.castFromStringToJSONNode(publicData);


        DBObject document = BasicDBObjectBuilder.start()
                .add("brand_id", twitterId)
                .add("date", day)
                .add("followers", publicDataJsonNode.get("followersCount").asText())
                .add("tweets", publicDataJsonNode.get("tweetsCount").asText())
                .get();

        twitterCollection.update(query,new BasicDBObject("$set", document), true, false);

    } catch (JSONParamsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
Sambhav Sharma
  • 5,741
  • 9
  • 53
  • 95

5 Answers5

3

The biggest disadvantage is that you may also catch an exception you didn't intend to catch.

For instance, let's say you have a method that may throw a NullPointerException, and you can handle that case. (Such a method is probably badly written, but let's say it's a library method and you can't change it.) So, you catch the NPE:

void func1() {
    try {
        func2();
        if (someString.equals("some value") {
            someOtherFunction();
        }
    } catch (NullPointerException e) {
        // handle func2()'s NPE somehow
    }

}

There are two places a NPE could have been thrown within the try's body: from func2, or from someString.equals if someString is null. This code treats both the same way, which is probably a bug.

Generally speaking, in nearly all aspects of programming (variable scope, try-catch blocks, class members, etc), the smaller the scope is, the easier it is to reason about and the less likely you are to write bugs.

yshavit
  • 42,327
  • 7
  • 87
  • 124
2

You can obviously use a try/catch block surrounding the entire body of the method, but confining it to the area that you are expecting an error adds readability to your code. I'm also fairly certain that they are very slow, and inefficient and there's no point to 'try' something where there's no possible IOException for example int i = 2 + 2;

Tom McGee
  • 136
  • 6
  • 3
    Just using a try-catch block isn't really slow, it's throwing (and logging) an exception that is slow. Interesting question about try-catch performance if no exception is thrown: http://stackoverflow.com/questions/16451777/is-it-expensive-to-use-try-catch-blocks-even-if-an-exception-is-never-thrown – nerdherd Jun 20 '14 at 20:36
  • Thanks for that I appreciate the link! Very interesting though that the compiler doesn't optimize code inside a try. – Tom McGee Jun 20 '14 at 20:40
2

I know from the coders perspective, where if an exception is thrown, he will be able to know exactly where the exception came from

You nailed it right there: when you write a method you create a contract between you and the user. If you declare that the method throws an exception - it will be the responsibility of the user to catch and handle that exception. If it makes sense - you should do it (for example, throw an exception if you failed opening a connection to the DB). That said, in other cases, you might want to preform a fallback and just report to the user if the action was successful or not, in that case you can surround all the code inside method2 with try/catch and return a boolean value to save your users the extra coding of handling the exception.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

well, if you have anything in funct1 after the call to funct2, that won't get executed if you place the whole method inside the try-catch.

Wcrousse
  • 203
  • 2
  • 10
0

im am citing Clean Code Book :

Error Handling Is One job, and functions should do one job. Thus, a function that handles errors should do nothing else. This implies (as in the example above) that 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.

so you should create a method that manages the exception , something like this:

public class Test {


  public void doSomthing(){

    // here i don't need to manage the exception because i have built parseDate(String date)
    Date date = parseDate("10-17-2016");

  }


  private Date parseDate(String date){
    Date result = null;
    try {
        result = new SimpleDateFormat().parse(date);//Throws Parse Exception
    } catch (ParseException e) {
        // Here you can:
        //1) Throws other exception (Checked or Unchecked)
        //2) Log the exception
        // I think you should not re-throws the exception because
        //is responsibility of this methods manage the exception
        e.printStackTrace();
    } 
    return result;
  }

}
Sambhav Sharma
  • 5,741
  • 9
  • 53
  • 95