Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?

user-image
Question added by Muhammed Rahshad Koyippalli , Cisco DNAC Senior Escalation Engineer , Cisco Systems - India
Date Posted: 2014/05/24
Abdulelah Fallatah
by Abdulelah Fallatah , Tech-Support Specialist & Programmer , Al-Rayan Colleges

System.exit(0) will terminate your program. In other words, it will not execute the lines below "System.exit(0)" even if a return statement was below "system.exit(0).

For the return statement, it'll stop executing the method block and exit. Ater the exit, the returned value will go to the method that called the method with that method block. For example, "System.out.println(string.length());"

Mohammed Ameen
by Mohammed Ameen , Java Developer , TATA Consultancy Services Limited (TCSL)

CASE1) If we write return at the end of the try block and no exception occurs,the finally block  will execute and then the control return.

CASE2) If we write System.exit(0) at the end of try block,the control immediately goes out of the program and thus finally never executes.

 

Finally block ll excute If you call the return statement from any of the try or catch block, but its not when we put System.exit on try or catch block. Becouse System.exit will quit  the program to run further.

Hamza Hasan
by Hamza Hasan , Backend Software Engineer , Shahid.net

If return is called in try or catch, finally block will execute

wherease calling System.exit(0) will cause termination current thread no matter what goes after it.

 

qaeed ramiwala
by qaeed ramiwala , Lead Java Developer / Software Engineer , CellPoint Mobile

Case1 : return in try or catch = finally block will execute

Case2 : System.exit(0) = will terminate current thread execution irrespective of what is expected from specification of flow.

Vivek Dudani
by Vivek Dudani , Software Engineer / Senior Software Engineer , Mastercard

The finally block will execute under all the conditions except for Sytem.exit(0) or you shutdown the JVM itself. So, even if there is a return statement in try block or catch block, finally block will still be executed.

Gurpreet kaur
by Gurpreet kaur , Software Developer , BlacknGreen Mobile Solutions Pvt. Ltd.

If you call return from catch it will still execute finally

But if call system.exit then it will not execute finally block

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.