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 (46.1k 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

+2 votes
2 answers
0 votes
1 answer
asked Aug 20, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...