This may be a strange question, but I still thought that I would ask you to get an idea about this and not to let me do something wrong while I was coding.
Let's say I have a func1 () function inside which I call func2 (). The func2 () function throws an exception e1. And I want to catch this exception inside func1 ().
Does it matter whether I start the try block at the beginning of the function itself and end it at the end of func1 () with the catch block, and not just surround the part of the code where I call the func2 () function.
I know from the point of view of coders where, if an exception occurs, he will be able to know exactly where the exception came from. If we ignore this, are there any other negative consequences of just putting the whole method inside try-catch?
Edit - code snippet
So, I am converting a JSON string to a JSON Node. This operation throws an exception. But instead of surrounding this single statement with a try-catch block, I put the whole function inside a 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) {
e.printStackTrace();
}
}
source
share