这是一个代码示例。如果我输入分子: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);
}
}
发布于 2012-09-02 20:52:04
我不确定你对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
。因此,它会在线程发生后简单地停止线程的执行,所以它不需要被捕获/抛出(当然,您仍然可以在方法之外捕获它,以防止线程停止)。
发布于 2012-09-02 20:54:03
ArithmeticException
和InputMismatchException
都是未检查的异常(RuntimeException
的子类型)。这意味着您不需要捕获或抛出它们,但是,您需要处理导致它们的情况。
例如,为了避免DivideByZeroException
(ArithmeticException
),您的程序必须检查分母是否不为零。如果是,就不要做除法运算。
发布于 2012-09-02 20:51:04
您不必在throws子句(v.g.,NullPointerException
)中声明从RuntimeExceptions
派生的异常。这就是为什么编译器不会告诉你必须声明它(对于其他异常,你会得到一个编译器错误/ IDE会在方法声明中发出错误的信号)。
当然,如果您正在调用的某个方法可能抛出它,您可以将其作为任何其他异常来捕获。
https://stackoverflow.com/questions/12239629
复制相似问题