I can\'t understand exactly how return
works in try
, catch
.
try
and finally
without
And if I have try, catch, finally I can't put return in the try block.
You absolutely can. You just need to make sure that every control path in your method is terminated properly. By that I mean: every execution path through your method either ends in a return
, or in a throw
.
For instance, the following works:
int foo() throws Exception { … }
int bar() throws Exception {
try {
final int i = foo();
return i;
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
System.out.println("finally");
}
}
Here, you’ve got two possible execution paths:
final int i = foo()
System.out.println("finally")
return i
System.out.println(e)
System.out.println("finally")
throw e
Path (1, 2) is taken if no exception is thrown by foo
. Path (1, 3) is taken if an exception is thrown. Note how, in both cases, the finally
block is executed before the method is left.