package com.ami.practice;
public class UnrechebleStatement {
public static void main(String[] args) {
System.out.println(m());
}
public static int m(){
try{
int x=0;
int y=10/x;
return y;
}catch(Exception e){
return 1;
}finally {
return 2;
}
}
}

- 12,158
- 7
- 41
- 68

- 33
- 5
-
9Because it's defined like that in the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2). – Robby Cornelissen Mar 17 '17 at 08:37
-
1http://stackoverflow.com/a/65049/4297364 – Moishe Lipsker Mar 17 '17 at 08:39
-
1Why do you think that keyword was named finally... – GhostCat Mar 17 '17 at 08:39
-
You may not return a value from a `finally` block. It is not not necessary and even more - it's a bad practice. It is usually used to free resources (for example closing streams). – Zefick Mar 17 '17 at 08:40
-
5Ah, but you _may_. You simply _shouldn't_. – Dawood ibn Kareem Mar 17 '17 at 08:41
-
thank u vry mch guys .... – Sagar Mahapatra Mar 17 '17 at 09:15
3 Answers
from the JLS#14.17
A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.
[...]
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks or catch clauses contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.
Especially the second part should perfectly answer your question

- 1
- 1

- 7,307
- 2
- 21
- 33
-
It looks good, can you explain the flow in context of the example code provided? Even though the finally is executed, the first return gets called, then the second return gets called. Why is the value from the second return used? – matt Mar 17 '17 at 08:54
-
@matt as the `JLS` states, the `return 1` attempts to transfer controll back to the caller, but the underlying `finally` `return 2` will abrupt the `catch` `return`, and will transfer the controll back with the value provided by the `return` provided in the `finally` clause. – SomeJavaGuy Mar 17 '17 at 09:20
Finally is always called except in some cases
1) if System.exit() is called
2) if jvm crashes
3) if we use nested try catch

- 811
- 1
- 9
- 27