-3

Why finally block of this code does not execute? it only prints 1. Is finally block not execute after System.exit(0); ?

    void method2() {
    try {
        System.out.println("1");
        System.exit(0);
    } finally {
        System.out.println("3");
    }
}
User3031
  • 19
  • 3
  • Code doesn't continue to execute after an application terminates. Why would you think otherwise? – David Nov 03 '15 at 19:57

4 Answers4

3

System.exit(0) actually stops execution of the program entirely. Remove System.exit as you aren't actually trying to exit your code there.

basic
  • 3,348
  • 3
  • 21
  • 36
1

Remove SYSTEM.EXIT because that exits the entire program regardless of what is after it. Though it is in a Try it still enters the block of code :)

colt
  • 116
  • 12
0

System.exit(0) terminates the runtime before the finally block is even executed. Move it to finally block after your System.out.

The Law
  • 344
  • 3
  • 20
0

System.exit(); shuts down the virtual machine. The only thing that can be executed after this is a shutdown hook created with Runtime.addShutdownHook(Thread).

Kayaman
  • 72,141
  • 5
  • 83
  • 121