异常,算术异常和对象

时间:2015-10-05 04:24:18

标签: java

当我运行下面的代码时,它给出输出"算术异常"。由于算术异常被检查为异常,因此它具有比未经检查的异常更高的优先级。 但它如何区分对象和算术异常?

public class Solution {


public static void a(Exception e)
{
    System.out.println("Exception");

}
public static void a(ArithmeticException ae)
{
    System.out.println("ArithmeticException");
}

public static void a(Object o)
{
    System.out.println("Object");
}

public static void main(String[] args)
{
    a(null);
}

}

2 个答案:

答案 0 :(得分:4)

当您重载方法时,将选择大多数特定方法。在您的情况下,选择的顺序是

Arithmetic Exception > Exception > Object

根据Language specification,大多数特定方法在运行时选择。

  

如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符。 Java编程语言使用选择最具体方法的规则。

Arithmetic ExceptionException更具体,比Object更具体

答案 1 :(得分:0)

Java语言将在方法重载的情况下选择最具体的匹配,这些参数通过继承相互关联。

我们将使用示例

来演示此行为
    public static void main(String[] args) {
        a(new Exception("some exception"));
        a(new ArithmeticException("something went wrong with numbers."));
        a(new String("hello world"));
        a(null);
    }

输出符合预期: enter image description here