尝试使用因子递归函数捕获异常

Jan*_*Poe 0 java methods try-catch

我希望我的factorial输出一个语句打印出"无效错误.没有负数"当我合并一个try -catch方法但每次它不打印我的错误语句.这是我的代码:

import java.util.Scanner;
import javax.swing.JOptionPane;

public class App {

public static void main(String[] args) {
    int value;
   //E.g. 4!=4*3*2*1
    Scanner keyboard=new Scanner(System.in);
    System.out.println("Enter a value for factorial");
    value=keyboard.nextInt();
    try{
    System.out.println(calculate(value));}catch(NumberFormatException e){

        System.out.println("invalid error. No negative numbers");

    }

}

private static int calculate(int value){


    if(value==1 || value==0){
        return 1;
    }
    return  calculate(value-1)*value;

}

}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么

Con*_*Del 5

你没有抛出异常

private static int calculate(int value) throws NumberFormatException {

    if (value < 0) throw new NumberFormatException("invalid error. No negative numbers");
    if(value==1 || value==0){
        return 1;
    }
    return  calculate(value-1)*value;

}
Run Code Online (Sandbox Code Playgroud)

  • `NumberFormatException`用于解析字符串.你应该使用`IllegalArgumentException` (3认同)