Can we write return statement in finally block
i)Return statement in finally block
ii) return statement in finally
iii) return statement in try catch and finally blocks
Output:
- Finally block will executes always excepts system.exit().
- So if we are returning some value in finally means it will be returned always
- Finally will executed so method always returns finally return value and no need of keeping return value at end of the method.
- And in finally after return if we keep some statement those statement will be treated as dead code.
i)Return statement in finally block
- package com.exceptionhandlingiinterviewquestions;
- public class TryCatchReturn{
- int calc(){
- try {
- } catch (Exception e) {
- }
- finally(){
- return 1;
- }
- System.out.println("End of the method"); // Error : Unreachable code
- }
- public static void main(String[] args) {
- TryCatchReturn obj = new TryCatchReturn();
- }
- }
- package com.exceptionhandlingiinterviewquestions;
- public class TryCatchReturn{
- int calc(){
- try {
- } catch (Exception e) {
- }
- finally(){
- return 1;
- System.out.println("End of the method"); // Error : Unreachable code
- }
- }
- public static void main(String[] args) {
- TryCatchReturn obj = new TryCatchReturn();
- }
- }
- package com.exceptionhandlingiinterviewquestions;
- public class TryCatchReturn{
- int calc(){
- try {
- return 10;
- } catch (Exception e) {
- return 20;
- }
- finally(){
- return 30;
- }
- }
- public static void main(String[] args) {
- TryCatchReturn obj = new TryCatchReturn();
- System.out.println(obj.calc())
- }
- }
Output:
- 30
Bagikan
Return statement in finally block in java
4/
5
Oleh
Kris Kimcil