如何抛出不会终止程序的IllegalArgumentException? [英] How do I Throw an IllegalArgumentException that won't terminate my program?

查看:162
本文介绍了如何抛出不会终止程序的IllegalArgumentException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我有一个带有switch语句的方法,但是我忽略了其余的情况,因为它们并不重要.在我的主要方法中,将调用操作符方法,并在while循环中传递参数选择",直到他们选择"Q"为止.

Ok so I have a method with a switch statement but I left out the rest of the cases because they're not important. In my main method, the operator method is called and passed the parameter "selection" in a while loop until they choose "Q".

当用户输入一个负数时,它应该引发异常,打印一条消息并忽略他们的输入,然后循环回到开头.引发此异常时,它将终止程序.任何帮助将不胜感激.谢谢!

When the user enters a negative number, it should throw an exception, print a message, and ignore their input but then loop back to the beginning. When this exception is thrown it terminates the program. Any help would be very much appreciated. Thanks!

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继承创建自己的Exception.

An IllegalArgumentException inherits from RuntimeException, for it not to stop your program you can just use a simple try{} catch {} but i don't recommend doing that with Runtime Exceptions. If that's the case, create your own Exception inheriting from java.lang.Exception.

您可以在此处使用try catch.

You can use try catch here.

类似的东西应该可以工作:

Something like this should work:

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继承(如果希望它停止程序运行),如下所示:

And to make your own Exception class you basically need to inherit from Exception (if you want to use try catch on it) or inherit from RuntimeException (if you want it to stop your program from running), like this:

public class NegativePriceException extends Exception {

  public NegativePriceException() {
     super();
  }
}

这篇关于如何抛出不会终止程序的IllegalArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆