Sambhav Sharma Sambhav Sharma - 1 year ago 99
Java Question

Java Try Catch Block Size

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())

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

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


Answer Source

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 {
        if (someString.equals("some value") {
    } 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download