System.exit(0) in java

后端 未结 5 1910
北恋
北恋 2021-01-02 07:41

I am writing an application program using swing. I need to exit from the application by clicking the JButton for that can i use System.exit() or sh

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 07:45

    In general, calling System.exit(...) anywhere but the "main" method of an application can be problematic for (at least) the following reasons.

    • It is an impediment to reusing your code.

    • It makes unit testing hard. For example, if your code calls System.exit when your JUnit tests exercise some error handling, that it the end of your test sequence!

    The specific case of calling System.exit(...) in the button listener for the "exit" button is not so bad. You are unlikely to want reuse the button listener somewhere that doesn't also require this behaviour. Also, you can probably figure out a work-around for the unit testing conundrum; e.g. don't unit test that particular method!

    However, I think I'd still try to get the exit happen a different way. For example, have the main method launch everything and then block on a CountDownLatch, then have the button listener decrement the latch. When the main method unblocks, it executes the relevant shutdown code and returns or exits as appropriate.

提交回复
热议问题