0

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?

  • The language facility for this are shutdown hooks, cf. http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java – Hein Blöd Aug 18 '15 at 19:49
  • When you say "test program is forced to finish", do you mean you kill the process? If you do, then no cleanup code can be run, because that's a hard kill. – Andreas Aug 18 '15 at 19:54

2 Answers2

0

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.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

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.

ansjob
  • 175
  • 7