2

I have a class- public class Check {

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


public boolean isRight(){
    try{
        return true;
    }finally{
        return false;
    }
}

The method isRight has return true and false in finally clause , and finally it returns me false as finally clause will surely be called, so whats actually happening the data inside try. I need to know the logical reason behind the output , I read but couldn;t understand properly.

8
  • 3
    Why would you write such a messy code? Commented Dec 7, 2013 at 14:54
  • possible duplicate of Strange finally behaviour? or Java-try-finally-return-design-question Commented Dec 7, 2013 at 14:54
  • i just want this info for learning . nothing about exact code Commented Dec 7, 2013 at 14:54
  • stackoverflow.com/questions/48088/… Commented Dec 7, 2013 at 14:55
  • 2
    @bunta Compiler throws a warning about the finally block not terminating properly, so even the compiler thinks this code is messsy. Commented Dec 7, 2013 at 14:56

3 Answers 3

5

finally will not be called only if you use System.exit() or JVM craches.

In all other cases, finally will be called, so false will be returned. How?

When the return in try is reached, the control transfers to finally, there you return false.. Simple.

Go through the official docs to better understand that.

Sign up to request clarification or add additional context in comments.

Comments

2

Your code always returns false because the finally block is always executed after try-catch statements are executed no matter what unless the JVM crashes or on System.exit() as others have already mentioned.

So, when the try block reaches the return true; statement the control is passed however to the finally block and it returns false (over-riding the previous true value).

Comments

0

false will be returned there. That's the idea of finally - it gets the last say on things. finally will be invoked and will return false as mentioned in your code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.