Link to home
Start Free TrialLog in
Avatar of Los Angeles1
Los Angeles1

asked on

Java, capturing a CTL-C in a hello world

I want to 'catch' when the user of my simple app hit's control C

I want to write a program that prints 'hello world" in an infinite loop, but trys to catch wehn a ctl C , or any other key, then prints that he is done and exits.

How can I do this
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

You'd have to wrap your code in a try - catch - finally block.
Here is some Q&D code for it :

import java.util.Scanner;



class TryCatchFinally_ContendingWithCTRL_C extends Thread
{
      public static void main (String [] args)
      {

            new TryCatchFinally_ContendingWithCTRL_C().start();
            Scanner keyIn = new Scanner(System.in);
            
            int n1 = 0;
           	              
                try{
                System.out.print("Enter a number: \n");
                n1 = keyIn.nextInt( );
            	}catch(Exception e){}finally{System.out.println("Finally caught when you pressed CTRL-C");}

      }

	public void run(){

		try{}catch(Exception e){}finally{System.out.println("Finally routine from run() method.");}

	}
}

Open in new window


The class extends thread and outputs a string when run() comes to a natural end. But when you get the prompt on the screen to enter a number, instead of entering an int, hit CTRL-C, and you should get the result you want.

BUT beware - the finally part *ALWAYS* gets run, even if there was no exception.
ASKER CERTIFIED SOLUTION
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Los Angeles1
Los Angeles1

ASKER

I tried the run() code, but when I hit a CTL-C, I still get the following

Terminate batch job (Y/N)? y

Open in new window

No real idea what you mean by your last comment. Where did you ever mention a batch job being involved?