如何抛出不会终止我的程序的 IllegalArgumentException?

Nic*_*llo 2 java exception try-catch throw

好吧,我有一个带有 switch 语句的方法,但我省略了其余的情况,因为它们并不重要。在我的主要方法中,调用运算符方法并在 while 循环中传递参数“选择”,直到他们选择“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);
}
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ian 5

IllegalArgumentException 继承自 RuntimeException,因为它不会停止您的程序,您只需使用简单的 try{} catch {} 但我不建议对运行时异常执行此操作。如果是这种情况,请创建您自己的继承自 java.lang.Exception 的 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);
}
}
Run Code Online (Sandbox Code Playgroud)

要创建自己的 Exception 类,您基本上需要从 Exception 继承(如果您想对其使用 try catch)或从 RuntimeException 继承(如果您希望它阻止程序运行),如下所示:

public class NegativePriceException extends Exception {

  public NegativePriceException() {
     super();
  }
}
Run Code Online (Sandbox Code Playgroud)