We help IT Professionals succeed at work.

Does Java catch a kill/term signal (crtl-c)???

mfischer2
mfischer2 asked
on
Is it possible to catch a kill or term signal with a Java exception handler?

I tried to catch it with InterruptedException and then just plain Exception.  However, this is the first time I have tried exceptions so maybe I am doing something wrong.

public class test {

public long counter=0;

public void run() throws InterruptedException {
  while (true) {
   while (counter < 1000000000) {
         counter++;    }
    counter=0;   }
        }

public static void main (String arvg[]) {

      test mytest = new test();
       try {
            mytest.run();       }

     catch (Exception foo) {
System.out.println("at interrupt, counter was" + mytest.counter);      }
        }
}

Comment
Watch Question

BRONZE EXPERT
Top Expert 2004
Commented:
You can do this:

    Runtime.getRuntime().addShutdownHook( new Thread()
            {
              public void run()
              {
                System.out.println( "Shutdown signal caught!" ) ;
              }
            } ) ;

Hope it helps :-)

Tim.
BRONZE EXPERT
Top Expert 2004

Commented:
Oh yeah, do it in the constructor of your class...

And you need JDK 1.2+  (I think)... I know it works with JDK 1.3 :-)

Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Points for TimYates

Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venabili
EE Cleanup Volunteer