Solved

Java, capturing a CTL-C in a hello world

Posted on 2013-01-04
6
378 Views
Last Modified: 2013-01-07
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
0
Comment
Question by:Los Angeles1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
6 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 38745457
You'd have to wrap your code in a try - catch - finally block.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38745489
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.
0
 
LVL 16

Accepted Solution

by:
krakatoa earned 500 total points
ID: 38745516
And so if you want a version that only catches the error, you'd do smthg like :

import java.util.Scanner;



class TryCatchFinally_ContendingWithCTRL_C extends Thread
{

 static boolean error = false;

      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){error=true;}finally{if(error){System.out.println("Finally caught when you pressed CTRL-C");}}

      }

	public void run(){

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

	}
}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 38746681
0
 

Author Comment

by:Los Angeles1
ID: 38751380
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

0
 
LVL 16

Expert Comment

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

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Is there a simpler dropbox system? 10 53
jsp CRUD operations with and without prepared statement also hibernatge 1 49
passing enum to a method 4 50
Java array 21 149
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question