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

标签 java exception try-catch throw

好吧,我有一个带有 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/

相关文章:

java - 可滚动 JTable : dispalying vertical scrollbar from the header level

java - Android:在单击按钮时获取 Spinner 的 Textview 值

java - 什么指的是我的文件,阻止我成功调用 .delete()?

java - 无法在child()错误中为参数“pathString”传递null

c# - DataContract 运行时错误 - 类型 'myType' 无法序列化。我做错了什么?

c# - 我应该如何在 Java 中复制 C#'s ' using' 语句的功能?

c# - 可以将 Application.Run() 方法放在 catch 中以避免应用程序终止吗?

c++ - 如何检查输出流是否为 C++ 中的 std::cout?

.net - 绿色异常(exception)?

Java 7 Try-With-Resources (AutoCloseable) 实现