Solved

Java, capturing a CTL-C in a hello world

Posted on 2013-01-04
6
379 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 17

Expert Comment

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

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 17

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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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 17

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

Industry Leaders: 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!

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

717 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