Exception 非常基本的java异常处理

Exception 非常基本的java异常处理,exception,exception-handling,Exception,Exception Handling,在divide方法中包含“throws arithmetricexception”声明有什么意义吗 try { divide(10,0); } catch(ArithmeticException e) { System.out.println("Exception caught."); } } public static void divide(int x, int y) throws ArithmeticEx

在divide方法中包含“throws arithmetricexception”声明有什么意义吗

    try
    {
        divide(10,0);
    }

    catch(ArithmeticException e)
    {
        System.out.println("Exception caught.");
    }

}

public static void divide(int x, int y) throws ArithmeticException
{
    int result = 0;

    result = x / y;
    System.out.println("Quotient is " + result);
    return;
}

其中一个原因是要了解您的除法是否以分母“0”完成。任何被0除的东西都是无穷大。您的程序将无法解释结果,因此divide方法将引发异常错误。

仅当除以零或使用BigDecimal而不是四舍五入时才会引发算术异常。因为您的divide方法使用的是“int”数据类型,所以我只使用一个if语句,它只允许您对y进行除法,而y不等于零


我注意到这是一个无效的方法,除了打印结果,你什么也不做。我不确定这是否是你的意图,但是如果你需要这个值,你应该考虑改写以满足你的需要。

确实取决于你想处理异常的地方。如果您是异常处理新手,那么这值得一看,并且有点娱乐性。