简体   繁体   中英

calling destructor to call a method before closing JAVA program

I am writing a test with Selenium and JAVA, sometimes when I get an error I use System.exit(1); to close my test or in some other situations my test program is forced to finish, but I need to run a function in any case before shutting the program down, so Is there any destructor in Java that if I call my function there it will be called (guaranteed) if any thing forces my program to finish?

What you are looking for is called a finalizer , or using a shutdown hook (see Useful example of a shutdown hook in Java? ), but you really shouldn't be doing that.....

Don't use System.exit(1) . Throw an exception and let it to roll back your call stack, allowing each method on the call stack to handle resource cleanup in a try-finally block.

You can always catch the exception in your main method and call System.exit(exitCode) there, if you need to control the exit code.

If you're using JUnit to drive your tests, you may be interested in using @Before and @After to annotate setup and teardown methods. And as Andreas was saying, you should be throwing exceptions instead, then JUnit will deal with calling the teardown methods even in case of errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM