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

标签 java exception

当发生异常时,我希望将用户返回到发生异常的代码行,而不是让他们再次输入所有内容。有没有一种简单/简单的方法可以做到这一点?

    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() 赋值。这可能会导致错误,因为输入并不总是 double ,但分配字符串要容易得多,并且不需要被捕获。要返回到该行,请将要在 while 循环中重复的行括起来。在循环内,使用 if 语句检查输入。当获得所需的输入时,使用break关键字结束循环。这将继续分配变量,直到它被分配到您想要的位置。 警惕不必要地使用异常。异常是对象,因此内存消耗更大。因此,仅当无法用程序逻辑处理错误时才使用异常。我并不是说你不应该使用异常,只是说你应该只在 if 语句无法处理错误的情况下使用它们。

关于java - 将用户返回到发生异常的代码行 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732116/

相关文章:

java - Log4j 2 的断路器

java - 如何用 Selenium 向右或向左滑动?

java - 无法编译 JSP : The type java. util.Map$Entry 的类无法解析。它是从所需的 .class 文件间接引用的

c# - 如何处理来自同一个异常对象的不同类型的异常?

c# - 捕获所有异常

exception - 处理错误-Elixir

java - 调用从 nashorn(JDK 8 JavaScript 引擎)获取 char[] 输入参数的 Java 函数?

java - 如何重叠 JPanel(背景)和 JTextField

python - 如何从 C 扩展引发 Python 异常

android - 为什么 "78.137.18"没有被拒绝为无效 IP 地址?