好吧,我有一个带有 switch 语句的方法,但我忽略了其余的情况,因为它们并不重要。在我的主要方法中,运算符方法被调用并在 while 循环中传递参数“selection”,直到他们选择“Q”。
当用户输入一个负数时,它应该抛出一个异常,打印一条消息,并忽略他们的输入,然后循环回到开头。当抛出此异常时,它会终止程序。任何帮助将不胜感激。谢谢!
public static void operator(String selection) throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
if(input.nextDouble()<0){
throw new IllegalArgumentException("Price cannot be a negative value");
}
else{
price = input.nextDouble();
}
break;
case"Q":
System.exit(0);
}
}
最佳答案
IllegalArgumentException 继承自 RuntimeException,因为它不会停止您的程序,您可以只使用简单的 try{} catch {} 但我不建议使用运行时异常来这样做。如果是这种情况,请创建您自己的继承自 java.lang.Exception 的异常。
你可以在这里使用try catch。
像这样的东西应该可以工作:
public static void operator(String selection) {
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
try {
if(input.nextDouble()<0) {
throw new NegativePriceException();
}
} catch (NegativePriceException e) {
System.out.println("The price can't be negative.");
e.printStackTrace();
}
price = input.nextDouble();
break;
case"Q":
System.exit(0);
}
}
要创建自己的 Exception 类,您基本上需要从 Exception 继承(如果您想对其使用 try catch)或从 RuntimeException 继承(如果您希望它停止程序运行),如下所示:
public class NegativePriceException extends Exception {
public NegativePriceException() {
super();
}
}
关于java - 如何抛出不会终止我的程序的 IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532490/