java - 为什么/何时添加 inputMismatchException?

标签 java exception

这是一个代码示例。如果我输入分子:5 分母:0

我遇到这样的异常:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionHandling.DivideByZeroExceptions.quotient(DivideByZeroExceptions.java:10)
at ExceptionHandling.DivideByZeroExceptions.main(DivideByZeroExceptions.java:22)

我知道我必须包括(抛出算术异常) 但是,我怎么知道我需要使用 inputMismatchException?

 // Try DivideByZeroExceptions

  public class DivideByZeroExceptions {

public static int quotient(int numerator, int denominator) {
    return numerator / denominator;
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Please enter an integer numerator: ");
    int numerator = input.nextInt();
    System.out.println("Please enter an integer denominator: ");
    int denominator = input.nextInt();

    int result = quotient(numerator, denominator);
    System.out.printf("\nResult: %d / %d = %d\n", numerator, denominator,
            result);

}

}

最佳答案

不确定您对 inputMismatchException 的具体要求,但这是您应该做的:

public static int quotient(int numerator, int denominator) {
    if(denominator == 0)
        throw new IllegalArgumentException("Cannot divide by 0!");
    return numerator / denominator;
}

IllegalArgumentException 扩展了 RuntimeException,而不仅仅是 Exception。因此,它会在发生后简单地停止线程的执行,因此不需要捕获/抛出它(当然您仍然可以在方法之外捕获它以防止线程停止)。

关于java - 为什么/何时添加 inputMismatchException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239629/

相关文章:

c++ - 使用不支持异常的 C++ 编译器?

exception - Meteor 抛出 throwIfSelectorIsNotId 异常

c++ - 在C++中,如果基类构造函数异常,那么构造函数和析构函数的顺序会是这样吗?

java - 带注释的剩余过滤器

java - 从mysql数据库获取数据后格式化

java - Selenium 不等待页面加载

php - Laravel 5. 异常处理程序/唯一数据库字段

java - 对空结果集的非法操作

java - 使用java windows应用程序获取mysql中两个日期之间的记录

java - jp2launcher.exe 不会随着小程序关闭而退出