我在我制作的控制台程序中出错,其中我似乎无法处理错误。Java错误处理 - 这是做这件事的最好方法吗?
如果用户输入了不正确的输入类型(如其中一个int去的浮动),他们被训斥和程序功能(即使该程序关闭时,它做它我方式):
while(!scanner.hasNextLong()){
System.out.println("You entered something bad.. Why do you hurt me?");
System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
try {
Thread.sleep(4000);
} catch (InterruptedException f) {
f.printStackTrace();
}
System.exit(0);
}
如果用户输入,例如,一个零作为一个变量,它不能等于零(由于零分裂),用户被训斥,和生命仍在继续,并且程序仍然功能:
while (b == 0) {
System.out.println("Did you even read the instructions?? You cannot divide by zero!");
System.out.println();
System.out.println("Second Integer: ");
b = scanner.nextLong();
}
但是,如果用户att空格除以零,则输入一个不正确的输入类型,程序崩溃。我究竟做错了什么?我试图进入一个try/catch- while循环,因为我在其他情况下没有,但它似乎并没有这样的伎俩:
System.out.println("Second Integer: ");
while(!scanner.hasNextLong()){
System.out.println("You entered something bad.. Why do you hurt me?");
System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
try {
Thread.sleep(4000);
} catch (InterruptedException f) {
f.printStackTrace();
}
System.exit(0);
}
b = scanner.nextLong();
while (b == 0) {
System.out.println("Did you even read the instructions?? You cannot divide by zero!");
System.out.println();
System.out.println("Second Integer: ");
b = scanner.nextLong();
}
你是什么意思,'崩溃'?你会得到一个异常和堆栈跟踪? – Kenney