为什么我不能从方法中抛出异常

问题描述 投票:0回答:3

我是 Java 新手,在抛出异常方面遇到了一些问题。也就是说,为什么这是不正确的

public static void divide(double x, double y) {
    if (y == 0){
        throw new Exception("Cannot divide by zero."); 
        // Generates error message that states the exception type is unhanded 
    }
    else
        System.out.println(x + " divided by " + y + " is " + x/y);
        // other code follows
}

但是这样可以吗?

public static void divide(double x, double y) {
    if (y == 0)
        throw new ArithmeticException("Cannot divide by zero.");
    else
        System.out.println(x + " divided by " + y + " is " + x/y);
        // other code follows
}
java exception try-catch block throw
3个回答
10
投票

ArithmeticException
是一个
RuntimeException
,因此不需要在
throws
子句中声明或由
catch
块捕获。但
Exception
不是
RuntimeException

JLS 第 11.2 节涵盖了这一点:

未经检查的异常类(§11.1.1)免于编译时检查。

“未经检查的异常类”包括

Error
RuntimeException

此外,您需要检查

y
是否为
0
,而不是
x / y
是否为
0


3
投票

您需要在方法签名中添加

throws
only 用于检查异常。例如:

public static void divide(double x, double y) throws Exception {
 ...
}

由于 ArithmeticException 扩展了 RuntimeException,因此第二个示例中不需要

throws

更多信息:


0
投票

Java 中抛出异常的方法必须在方法签名中删除它

public static void divide(double x, double y) throws Exception

如果没有声明,你的代码将无法编译。

有一个特殊的异常子集扩展了

RuntimeException
类。这些异常不需要在方法签名中声明。

ArithmeticException
延伸
RuntimeException

© www.soinside.com 2019 - 2024. All rights reserved.