Reputation: 2349
Is there any difference between following two methods?
Which one is preferable and why?
Prg1:
public static boolean test() throws Exception {
try {
doSomething();
return true;
} catch (Exception e) {
throw new Exception("No!");
}
}
Prg2:
public static boolean test() throws Exception {
try {
doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return true;
}
Upvotes: 21
Views: 7891
Reputation: 1537
I'm assuming this is a general question. Otherwise I might comment on other aspects of your method(s).
I think in the case or small methods like these it doesn't really matter. The method is short enough to understand immediately what's going on, what's related to what etc.
However, in the case of longer methods the flow is much easier to follow in the first example. In my opinion. It keeps together related code and related scenarios. When you're reading the method, the normal execution flow is not broken by the catch
block, making it more obvious and "fluent".
public static boolean test() throws Exception {
try {
doSomething();
return true;
} catch (Exception e) {
throw new Exception("No!");
}
}
But I won't generalize this for all methods; it's all about the context.
Upvotes: 2
Reputation: 33875
Consider these cases where you're not returning a constant expression:
Case 1:
public static Val test() throws Exception {
try {
return doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
// Unreachable code goes here
}
Case 2:
public static Val test() throws Exception {
Val toReturn = null;
try {
toReturn = doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return toReturn;
}
I would prefer the first one. The second is more verbose and might cause some confusion when debugging.
If test()
incorrectly returns null
, and you see toReturn
being initialized to null
, you might think the problem is in test()
(especially when test()
is not just a simple example like this).
Even though it can only return null
if doSomething
returns null
. But that might be hard to see at a glance.
You could then argue that, for consistency's sake, it's better to always use the first form.
Upvotes: 24
Reputation: 74
Nope there is no difference between both the methods. It will return true value in both the cases effectively by resuming the flow of the program as soon an and exception is handled. Catch will be accessed only when an exception occurs.
Upvotes: 4