java - 捕获 IllegalArgumentException?

标签 java exception try-catch factorial

我这里遇到了一点问题。我想弄清楚如何捕获 IllegalArgumentException。对于我的程序,如果用户输入负整数,程序应该捕获 IllegalArgumentException 并询问用户是否要重试。但是当抛出异常时,它不会提供该选项。它就这样终止了。我尝试使用 try 和 catch 方法,但它对我不起作用。如何捕获此特定异常以继续运行而不是终止?

public static void main(String[] args) throws IllegalArgumentException
{
    String keepGoing = "y";
    Scanner scan = new Scanner(System.in);
    while(keepGoing.equals("y") || keepGoing.equals("Y"))
    {
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
}

}

public class MathUtils
{
    public static int factorial(int n)
    {
        int fac = 1;
        for(int i = n; i > 0; i--)
        {
            fac *= i;
        }
        return fac;
    }
}

最佳答案

您需要在循环内添加 try catch block 以继续循环的工作。一旦遇到非法参数异常,就会在 catch block 中捕获它并询问用户是否要继续

import java.util.Scanner;

public class Test {
public static void main(String[] args) 
{
String keepGoing = "y";
populate(keepGoing);

}

static void populate( String keepGoing){
  Scanner scan = new Scanner(System.in);
 while(keepGoing.equalsIgnoreCase("y")){
     try{
        System.out.println("Enter an integer: ");
        int val = scan.nextInt();
        if (val < 0)
        {
            throw new IllegalArgumentException
            ("value must be non-negative");
        }
        System.out.println("Factorial (" + val + ") = "+ MathUtils.factorial(val));
        System.out.println("Another factorial? (y/n)");
        keepGoing = scan.next();
    }
    catch(IllegalArgumentException i){
        System.out.println("Negative encouneterd. Want to Continue");
        keepGoing = scan.next();
        if(keepGoing.equalsIgnoreCase("Y")){
        populate(keepGoing);
        }
    }
    }
}
}

希望这有帮助。 快乐学习:)

关于java - 捕获 IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26960941/

相关文章:

java - 如何将Android ImageButton的位图更改为R.Layout中存储的另一个位图

java - 如何避免 hierynomus ssh 中的非法 key 大小警告

Java执行器: How to notify a single waiting thread within the executer?

java - Groovy 异常后重试

c# - C# 中嵌套的 try-finally

PHP try-catch block : are they able to catch invalid arg types?

java - Wildfly 10.0.0 最终版是否像Tomcat一样支持OCSP?

java - 在 Windows 中从命令行执行 java 程序失败

c# - 传递给构造函数的空\null 字符串的更正异常

java - 为什么 getFraction1 和 getFraction2 方法没有正确设置这些变量的值?