Thursday, October 8, 2009

Never use System.exit(1) in a groovy script

I wrote a small groovy script to to do some maintenance tasks on my machine. At some point the logic got a little bit more complicated and I decided to write some simple testcases. I executed the testscript and was really surprised about the output: the test should fail but it didn‘t! Now I tried to nail it down with limiting the scope to a very simple method call but the result was exactly the same. Hm, I thought it must have something todo with log4j that I used to write everything into the logfile. So I removed the log4j dependency and started the tests again. To my surprise the result didn‘t change at all. There was no output from junit on the console. I started to look a little bit closer at the class and walked through the constructor call to the method that I called during my test. Bang! There is was! In the constructor I checked for the existence of a certain resource (in this case a mounted volume). If the volume wasn‘t mounted I terminated the script with System.exit(1). I guess this was a really bad idea. Now I changed it to throw new RuntimeException(‘Volume not mounted‘) and everything is fine again.
Lesson learned: Never call System.exit(1) in constructor calls!

2 comments:

Ken Wood said...

FYI a note regarding gradle, a groovy based build tool.

If you are running 'gradle --daemon ' and use System.exit(), it causes the daemon to crash. Since the whole point of using the daemon is to reduce startup time each time you run the script, it rather defeats the purpose.

Ingo Richter said...

Thank for the tip. I didn't noticed that. I haven't used gradle in a while. The script that caused the issue, was called during a build job. We haven't used gradle at that time and in the context of a build job, the daemon might not have helped to prevent that issue.