java - int 的三个异常(exception)

标签 java exception

我正在尝试创建一个代码,其中应该输入 int,然后如果 int 不在 9 到 99 之间则有异常,如果输入 double 而不是 int,则有另一个异常,如果输入了 double 则有第三个异常输入字符串。我该怎么做呢?我到目前为止所拥有的内容如下,但不知道如何纠正它。谢谢

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean correct = true;
    do {
        try {
            System.out.println("Enter an Integer between 9 and 99");
            int number = input.nextInt();
            if (number >= 9 && number <= 99) {
                System.out.println("Thank you, Initialization completed");
                correct = false;
            } else if (number < 9 || number > 99) {
                throw new Exception("Integer is not within the range");
            }
            if (input.hasNextDouble()) {
                throw new Exception("Integer not entered");
            } else {
                correct = false;
            }
            if (input.hasNext("")) {
                throw new NumberFormatException("Integer not entered");
            } else {
                correct = false;
            }
        } // check for range
        catch (Exception e1) {
            System.out.println("Number is not within 9 and 99");
            System.out.println();
            input.nextLine();
        } catch (Exception e2) {
            System.out.println("An integer was not entered");
            System.out.println();
            input.nextLine();
        } catch (NumberFormatException e3) {
            System.out.println("An integer was not entered");
            System.out.println();
            input.nextLine();
        }
    } while (correct);
}

最佳答案

方法.getMessage()返回构造函数中给出的字符串:

throw new Exception("HERE");

当您捕获 Exception 时,您还会捕获 NumberFormatException、InputMismatchException 等。 所以你必须最后捕获更广泛的。

catch (NumberFormatException e3) { // Precisier goes first
    System.out.println("An integer was not entered");
    System.out.println();
    input.nextLine();
}
catch (Exception e1) {
    System.out.println(e1.getMessage());
    System.out.println();
    input.nextLine();
}

关于java - int 的三个异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896308/

相关文章:

java - 你什么时候使用 Java 的 @Override 注解,为什么?

java - 每当我运行测试用例时都会出现 java.net.ConnectException

JavaFX Maven 插件部署 .deb 而不是 .exe 文件

java - 处理java异常

java - 尽管 RuntimeExceptions 扩展了 Exception 类,但编译器如何不检查它们?

c++ - typedef std::runtime_error MyError 与类 MyError:public std::runtime_error

Python、Django : catch SMTPRecipientsRefused. 改为获取 "undefined variable"

java - Spark : Read by S3 aws-sdk or as RDD

java - 如何在if else语句中覆盖java中的变量值

c# - 在哪里处理 StaleObjectStateException