首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >为什么/何时添加inputMismatchException?

为什么/何时添加inputMismatchException?
EN

Stack Overflow用户
提问于 2012-09-02 20:48:14
回答 3查看 714关注 0票数 0

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

我得到了这样的异常:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionHandling.DivideByZeroExceptions.quotient(DivideByZeroExceptions.java:10)
at ExceptionHandling.DivideByZeroExceptions.main(DivideByZeroExceptions.java:22)

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 // 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);

}

}

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-02 20:52:04

我不确定你对inputMismatchException的要求是什么,但这是你应该做的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static int quotient(int numerator, int denominator) {
    if(denominator == 0)
        throw new IllegalArgumentException("Cannot divide by 0!");
    return numerator / denominator;
}

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

票数 2
EN

Stack Overflow用户

发布于 2012-09-02 20:54:03

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

例如,为了避免DivideByZeroException (ArithmeticException),您的程序必须检查分母是否不为零。如果是,就不要做除法运算。

票数 2
EN

Stack Overflow用户

发布于 2012-09-02 20:51:04

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

当然,如果您正在调用的某个方法可能抛出它,您可以将其作为任何其他异常来捕获。

检查RuntimeException

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12239629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文