为什么/何时添加inputMismatchException?

时间:2012-09-02 20:48:14

标签: java exception exception-handling

这是一个代码示例。如果我要输入分子: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);

}

}

3 个答案:

答案 0 :(得分:2)

不确定您对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。因此,它只会在线程发生后停止执行,所以它不需要被捕获/抛出(当然你仍然可以在方法之外捕获它以防止线程停止)。

答案 1 :(得分:2)

ArithmeticExceptionInputMismatchException都是未经检查的例外(RuntimeException的子类型)。这意味着您不需要捕获或抛出它们,但是,您需要处理导致它们的情况。

例如,为了避免DivideByZeroExceptionArithmeticException),您的程序必须检查分母是否为零。如果是,请不要进行划分。

答案 2 :(得分:1)

您不必在throws子句(v.g.,RuntimeExceptions)中声明从NullPointerException派生的异常。这就是为什么编译器不会告诉你必须声明它(对于其他异常,你会得到编译器错误/ IDE会在方法声明中发出错误信号)。

当然,如果您调用的方法之一可能会抛出它,您可以将其捕获为任何其他异常。

检查RuntimeException