I made some simple code and it should have worked just fine. Problem was, it didn't. It took me some time to figure out what is the cause of number format exception. Apparently, when i try to type letters instead of numbers it should ask me to re-enter it again, but it crashes. But when i delete e.printStackTrace(); it's working just fine. Can someone tell me why?
import java.util.Scanner;
public class Test {
public static boolean isInteger(String strNumber) {
try {
int number = Integer.parseInt(strNumber);
if(number > 0) {
return true;
}
return false;
} catch (NumberFormatException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
String numberString = null;
int number = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter integer:");
numberString = scanner.nextLine();
} while(!isInteger(numberString));
number = Integer.parseInt(numberString);
System.out.println("Your number is: " + number);
scanner.close();
}
}
I believe that your program is still running. e.printStackTrace()
displays the same kind of output as your program would if the exception were not caught.
Example:
`java.lang.NumberFormatException: For input string: "asdf"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Test.isInteger(Test.java:7)
at Test.main(Test.java:29)`
Also, you might not see "Enter integer: "
after the debug output as the stream it is sent to, System.err
, is separate from System.out
, the regular printing stream. This means that sometimes, prints to System.err and System.out don't always appear in the same order that they are called in.
All of this is to say that your program is likely still running. It just looks like a crash since e.printStackTrace()
prints the same info you would get in the event of an uncaught exception that caused a crash.