1

my question is simple. How to force JAVA to terminate the program I am writing when any Exception occures?

I am currenlty using Swing and when a NullPointer exception is thrown, the program keeps on running in the background :| While running this way I can only close it from the task manager. The bad thing is that when I run the same program again, a second instance is created and I don't know why, but when I have more than 1 instance of the same program, one time I get null exception, next time not, next time yes, next time not.... Complete randomness.

Thanks in advance!

Tony Bogdanov
  • 7,436
  • 10
  • 49
  • 80

3 Answers3

4

This article will be of interest wrt. catching exceptions (which, ideally, you should be eliminating).

The idea is that you can plug in a proxy to wrap the invocation of the Swing event, and catch any resultant exceptions. You can then decide what to do - alert someone, exit etc.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • @BrianAgnew Good find. I thought you could do something like that in Swing, but wasn't sure. – Mac Oct 12 '11 at 18:14
  • yes but required test `if (SwingUtilities.isEventDispatchThread()) {` before call `push()`, because this code push new events to the EDT, without any care if some events in EDT waits, dispashing, exist or not – mKorbel Oct 12 '11 at 19:05
2

Obviously it seems that your program has at least a bug that you can try to iron out with a debugger.

As for your question, an exception will terminate your program if it isn't caught. So if you always throw your exceptions, including in the main method, when one happen will cause the program to exit.

However, as Mac said in the comment

A Swing app has an event loop in the way. The event loop catches Throwable (I believe), so he can't exactly control what's caught in the normal way.

stivlo
  • 83,644
  • 31
  • 142
  • 199
  • 3
    A Swing app has an event loop in the way. The event loop catches `Throwable` (I believe), so he can't exactly control what's caught in the normal way. – Mac Oct 12 '11 at 18:11
  • great @Mac, why don't you make it an answer. – stivlo Oct 12 '11 at 18:13
  • I knew what the problem was, but not really how to fix it. I just didn't want the poster to pull his hair out wondering how he can propagate exceptions in the event loop up to his main method. – Mac Oct 12 '11 at 18:17
  • @Mac Look at this http://stackoverflow.com/questions/740418/how-do-i-catch-this-exception-in-swing – stivlo Oct 12 '11 at 18:19
0

You should fix your bugs in your program. An exception will terminate the program if it isn't caught, you are probably catching the exception. You can always exit a program with System.exit(0);

Mob
  • 10,958
  • 6
  • 41
  • 58