Model N Interview Question: If we write return statement ... | Glassdoor.co.in

Interview Question

Senior Member of Technical Staff Interview Hyderabad

If we write return statement in try, catch and finally

  block, which one will execute when and why ?
Tags:
java
Answer

Interview Answer

4 Answers

0

The return written in finally will take precedence over others.

Interview Candidate on 08-May-2012
0

public class trycatch {
    public static void main(String[] args) {
        trycatch tc = new trycatch();
        System.out.println(tc.tryCatch());
    }
    public int tryCatch(){
        try{
            //return 1;
            System.out.println("try");
            throw new Exception();
        }catch(Exception e){
            System.out.println("catch");
            return 2;
        }finally{
            System.out.println("finally");
            return 3;
        }
    }

}
    Output:
try
catch
finally
3

Anonymous on 01-Oct-2012
0

Finally block will definitely execute, because it always gets executed and very important code is to be put in finally block like closing of file, return statement etc.

Saksham on 29-Jun-2015
0

public class TryCatch {

    public static int getReturn() {
        try {
            return 1;
        }
        catch(Exception e) {
            return 2;
        }
        finally {
            return 3;
        }
    }

    public static void main(String[] args) {
        System.out.println(getReturn());
    }

}

3 will be returned.

Anonymous on 19-Oct-2016

Add Answers or Comments

To comment on this, Sign In or Sign Up.