将用户返回到发生异常的代码行 - Java

Returning user to line of code where exception occurred - Java

当发生异常时,我希望 return 用户转到发生异常的代码行,而不是让他们再次输入所有内容。有 easy/simple 的方法吗?

    Scanner input = new Scanner(System.in);
    double initialAmount = 0.0;
    String type = "";
    double interestRate = 0.0;
    boolean finished = false;

    try{
        System.out.print("\nInitial Amount: ");
        input = new Scanner(System.in);
        initialAmount = input.nextDouble();

        System.out.print("Compound/Simple: ");
        input = new Scanner(System.in);
        type = input.nextLine();

        if (!type.equalsIgnoreCase("compound") && !type.equalsIgnoreCase("simple")){ 
            System.out.println(type);
            throw new IllegalArgumentException();
        }

        System.out.print("Interest Rate: ");
        input = new Scanner(System.in);
        interestRate = input.nextDouble();

        finished = true;
    }
    catch(Exception e) {
        System.out.print("\n----- Please check that you have entered a corrrect value! -----\n");
        createUserInvestment(); 
    }
    Investment invest = new Investment(interestRate, initialAmount, type);
    return invest;

您似乎在尝试验证输入,只是循环直到用户提供有效值。最好不要抛出异常,因为这是一个错误指示,你不能回到完全相同的行,程序是一个流程......循环输入,检查是否有效,打破循环有效时

没有必要在代码中抛出任何异常。唯一需要 try/catch 的代码是 nextDouble() 赋值。这可能会导致错误,因为输入并不总是双精度的,但分配字符串要容易得多,而且不需要捕获。要 return 到该行,将要在 while 循环中重复的行包围起来。在循环中,使用 if 语句检查输入。当你得到你想要的输入时,用 break 关键字结束循环。这将继续分配变量,直到它被分配给你想要的。 警惕不必要地使用异常。异常是对象,因此在内存上更昂贵。因此,仅当您无法使用程序逻辑处理错误时才使用异常。我并不是说您不应该使用异常,只是说您应该只在无法使用 if 语句处理错误的情况下使用它们。