java - 将 null 传递给 java 中的重载方法 |重载的变量是Exception类型

标签 java exception exception-handling

我正在用 Java 练习一些示例。代码如下所示:

public class NullPassing {
    public static void main(String[] args) {
        method1(null);
    }
    public static void method1(Exception e) {
        System.out.println(e);
    }
    public static void method1(ArithmeticException e) {
        System.out.println(e);
    }
}

我对此有几个问题,

1) 上面的代码使用 method1(ArithmeticException e) 执行并打印 null,为什么不使用 Exception(因为它位于层次结构的顶部)?

猜测:是不是因为ArithmeticExceptionException更具体。如果是这样,为什么问题2

2) 通过在现有代码中引入如下方法,程序出现编译时异常。为什么?

public static void method1(NullPointerException e) {
    System.out.println(e);
}

帮我学习。谢谢

最佳答案

您对 1 的回答是正确的。如果选择两个或多个重载作为候选,并且其中一个比所有其他重载都更具体,则选择最具体的一个。

JLS 是这样说的(Section 15.12.2.5):

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen. The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

(然后正式解释“更具体”的含义。)


在你的第二个案例/问题中,你有这个:

public class NullPassing {
    public static void main(String[] args) {
        method1(null);
    }
    public static void method1(Exception e) {
        System.out.println(e);
    }
    public static void method1(ArithmeticException e) {
        System.out.println(e);
    }
    public static void method1(NullPointerException e) {
        System.out.println(e);
    }  
}

现在我们有三个候选方法(“可访问且适用”的方法)。第一个不如其他两个具体,但剩下的两个候选人都不比另一个更具体。因此这是一个编译错误。

显然,您可以通过转换 null消除调用的歧义;例如

  method1((NullPointerException)null)

关于java - 将 null 传递给 java 中的重载方法 |重载的变量是Exception类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505126/

相关文章:

java - Primefaces 异常 INFO : java. lang.ArithmeticException :/by zero java. lang.ArithmeticException:/by zero

c++ - 禁用 C++ 异常,如何使任何 std::throw() 立即终止?

java - Eclipse ASTParser 只解析一个java 函数?

Java - ArrayList remove() 不起作用[传递字符串]

java - 使用 sparql 查询向 Fuseki 插入数据

java异常抛出返回

c++ - 当构造函数抛出异常时,构造函数中分配的内存如何释放?

Python:在此示例中抛出异常是正确的用例吗?

android - 安装异常设备未找到 ANDROID

.NET 捕获一般异常