Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {

something(); return success;

}

catch (Exception e) {

return failure;

}

finally {

System.out.println("xyz");

}

1 Answer

0 votes
by (46k points)

Yes, finally block will be executed and it won't depend on any function or so.

Try to execute this code in your compiler:

Input:

public static void main(String[] args)

{

   System.out.println(Test.test());

}

public static int test()

{

   Try

{

       return 0;

   }

   finally

{

       System.out.println("xyz");

   }

}

Output:

xyz

0

Hence it's proved from the example above.

The cases where finally won't work are:

  • If JVM crashes first
  • If System.exit() is invoked

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...