使用关键字throws来声明抛出运行时异常

mci*_*hak 5 java exception-handling

对我来说,这些代码

static int faktorial (int n) throws ArithmeticException {
  if ((n < 0) || (n > 31)) { 
    throw new ArithmeticException();
  } 
  if (n > 1) {
    return n * faktorial(n - 1);
  } 
  else {
    return 1;
  }    
}
Run Code Online (Sandbox Code Playgroud)

没有相同的代码

throws ArithmeticException
Run Code Online (Sandbox Code Playgroud)

当我使用以下代码时,请执行相同的操作:

public static void main(String[] args) {
  try {
    int n;
    Scanner sc = new Scanner(System.in);  

    System.out.print("Insert integer number: ");        
    n = sc.nextInt();         
    System.out.println(n + "! = " + faktorial(n));
  }
  catch (InputMismatchException e) {
    System.out.println("Not an integer number!");
    e. printStackTrace();
  }
  catch (RuntimeException e) {
    System.out.println("Number is too big!");
    e. printStackTrace();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有人使用,可能有人形容我

    throws ArithmeticException
Run Code Online (Sandbox Code Playgroud)

在我的代码中有一些优点.

我还要感谢一些使用关键字的好例子throws.非常感谢你!

NPE*_*NPE 9

由于ArithmeticException未经检查的异常,因此throws就编译器而言,将其列在规范中没有任何影响.

尽管如此,我认为保留throws规范用于文档目的是一个好主意.

也就是说,ArithmeticException当使用无效参数调用函数时,可能不是正确的异常.使用IllegalArgumentException会更合适.