Assume that I want to exit a console program if the user entered the char f, and in any time of the program. The user is supposed to enter some info but I want for each step he entering the input to be able to stop开发者_如何学C all the operation if he entered "f"? How can I do that? Should it be something like:
try
{
if (userchoice.equals("F"))
{
throw new exception e;
}
}
catch (exception e)
{
System.exit(1);
}
Thanks
You can throw the exception, unless it is caught it will cause the current thread to die.
if ("f".equalsCaseIgnore(userchoice))
throw new IllegalArgumentException("Option "+userchoice+" not allowed.");
Here's the correct syntax:
try {
if (userchoice.equals("F")) {
throw new Exception();
}
} catch (Exception e){
System.exit(1);
}
Hint:
Scanner
classSystem.exit();
The input of the char "f" is expected behavior and so throwing an exception may be wrong way.
Encapsulate your input in a method which is responsible to handle the input and decided behavior.
Just call system.exit() here if the user entered "f" or call an exit method that does the work.
Do the following.
- Read the input from the command line using classes like
BufferedReader
orScanner
. - Check for the character "f" from the i/p'ed string.
- Throw your exception using
throw new MyException();
- Catch the exception in the catch block and terminate it with
System.exit(1);
If you require "f" or "F", use equalsIgnoreCase()
function.
Try something like this,
try{
if (userchoice.equals("F")) {
throw new MyException;
}
}
catch (MyException e) {
System.out.println("MyException caught because i/p character was F" + e);
System.exit(1);
}
精彩评论