Can we use return statement in finally block. Can this cause any problem?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Yes you can,But you should not 1 ,because the finally block is meant for a special purpose.
Writing your logic inside it is not recommended.
You can write
return
statement infinally
block but the value returned fromtry
block will be updated on the stack and not thefinally
block return value.Let us say you have this function
and you are calling this from main method
This prints
Returning from inside a
finally
block will causeexceptions
to be lost.A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.
According to the Java Language Specification:
Note: As per JLS 14.17 - a return statement always completes abruptly.
Yes you can write the return statement in a finally block and it will override the other return value.
EDIT:
For example in below code
The output is always 2, as we are returning 2 from the finally block. Remember the finally always executes whether there is a exception or not. So when the finally block runs it will override the return value of others. Writing return statements in finally block is not required, in fact you should not write it.