Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...