Java递归和异常

时间:2016-03-30 02:34:08

标签: java exception recursion

我目前正在完成我的编程任务,据说使用递归来查找用户输入的数字的阶乘。我成功地完成了它并且它有效,但我决定扩展代码并添加一个例外的踢。

基本上我希望程序提示用户输入大于或等于0的数字,如果用户输入的数字小于0,我希望抛出,捕获和处理异常。我知道在这段代码中我使用的是StringTooLong不正确的异常,但我不知道其他任何例外情况。顺便说一下,当我运行我的代码时,我得到一个错误,在throw lengthException找不到符号。

这是我的代码:

import java.util.Scanner;

public class Recursion {

   public static void main(String args[]) {
      long userNum;
      System.out.println("Enter a number to check it's factorial");
      Scanner scnr = new Scanner(System.in);
      userNum = scnr.nextLong();
      StringTooLongException lengthException =
         new StringTooLongException ("String has too many characters");

      System.out.println(fact(userNum));
   }

   public static long fact(long userNum) {
      try {
         if(userNum < 0) {
            throw lengthException;
         } else if(userNum == 1 || userNum == 0) {
            return 1;
         } else {
            return userNum*fact(userNum-1);
         }
      } catch(Exception e) {
         System.out.println("Enter a number that is greater or equal to 0," + e);
      }

   }
}

4 个答案:

答案 0 :(得分:2)

尝试:

throw new StringTooLongException();

您可以删除以下内容:

StringTooLongException lengthException =
new StringTooLongException ("String has too many characters");

虽然正如@KevinO和其他人所建议的那样,更适合使用IllegalArgumentException,例如。

throw new IllegalArgumentException();

或者,您可以创建自己的自定义Exception,例如

public class InvalidInputException extends Exception {
    public InvalidInputException(String message) {
        super(message);
    }
}

您已在lengthException中声明main,并尝试在fact中使用它。因此,它超出了方法fact(long userNum)的范围。因此你得到的错误。

您可以在exceptions上查看this了解更多信息。

答案 1 :(得分:0)

您需要使用 new 来修复throw lengthException错误。另外我认为您打算使用&#39;抛出新的StringTooLongException();&#39;

您还应该了解有关异常是什么以及它的用途的更多信息。有一件事是Exception实际上是一个类,Exception类的任何子类本身都是一个Exception。因此,如果您愿意,可以通过简单地扩展Exception类来创建自己的异常。这就是为什么你必须在抛出异常时使用new关键字:你抛出一个新的异常实例(或其子类之一)。

您可以通过浏览JavaDoc for the Exception class中的直接已知子类部分来查看一些顶级异常的列表。

答案 2 :(得分:0)

您可以使用NumberFormatException

...
if(userNum <= 0) 
{
    throw new NumberFormatException("Must be a positive integer");
}
...
} catch (NumberFormatException e) {
    System.err.println("Enter a number that is greater or equal to 0," + e);
}

答案 3 :(得分:0)

实施的一个干净的替代方案是创建符合您要求的自定义异常。

例如,您可以按如下方式创建自定义异常类:

public class InvalidInputException() extends Exception
{
    public InvalidInputException()
    {
        super();
    }

    public InvalidInputException(String message)
    {
        super(message);
    }
}

此实现允许您在try-catch块中throw new InvalidInputException(),并为用户提供更多信息。