Is it possible to call the main(String[] args) after catching an exception?
I'm working on a Serpinski triangle program that asks the user for t开发者_Python百科he levels of triangles to draw. In the interests of idiot-proofing my program, I put this in:
Scanner input= new Scanner(System.in);
System.out.println(msg);
try {
level= input.nextInt();
} catch (Exception e) {
System.out.print(warning);
//restart main method
}
Is it possible, if the user punches in a letter or symbol, to restart the main method after the exception has been caught?
You can prevent the Scanner
from throwing InputMismatchException
by using hasNextInt()
:
if (input.hasNextInt()) {
level = input.nextInt();
...
}
This is an often forgotten fact: you can always prevent a Scanner
from throwing InputMismatchException
on nextXXX()
by first ensuring hasNextXXX()
.
But to answer your question, yes, you can invoke main(String[])
just like any other method.
See also
- (Java) Opinion: Preventing Exceptions vs. Catching Exceptions
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Note: to use hasNextXXX()
in a loop, you have to skip past the "garbage" input that causes it to return false
. You can do this by, say, calling and discarding nextLine()
.
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine(); // discard!
}
int i = sc.nextInt(); // guaranteed not to throw InputMismatchException
Well, you can call it recursively: main(args)
, but you'd better use a while
loop.
You much better want to do this:
boolean loop = true;
Scanner input= new Scanner(System.in);
System.out.println(msg);
do{
try {
level= input.nextInt();
loop = false;
} catch (Exception e) {
System.out.print(warning);
//restart main method
loop = true;
}
while(loop);
精彩评论