2015-10-05 105 views
0

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

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); 
} 

}

+1

下面的答案是正确的。你也应该注意到'ArithmeticException'不是一个检查的异常。 –

+1

[方法重载和选择最具体类型]的可能重复(http://stackoverflow.com/questions/9361639/method-overloading-and-choosing-the-most-specific-type) –

回答

4

当重载方法,最具体的方法将作为选。根据你的情况选择的顺序是

Arithmetic Exception > Exception > Object 

Language specification最具体的方法选择在运行时。

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

Arithmetic ExceptionExceptionObject

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