Solved

Java, capturing a CTL-C in a hello world

Posted on 2013-01-04
6
376 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
  • 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Apps blocked by Java 9 88
How to determine if a string is a valid SHA value 7 35
Java: The Public Class Main 4 30
servlet and mdb, jms error 1 32
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 …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

856 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