【发布时间】:2015-01-22 22:26:19
【问题描述】:
请在下面检查我的自定义异常:
public class ReportException extends Exception {
private int mCode = -1;
private String mString = "";
public ReportException(int code, String description)
{
super(description);
mCode = code;
mString = description;
}
public int getCode()
{
return mCode;
}
public String getString()
{
return mString;
}
}
我的问题是为什么这在另一个类中是非法的:
try{
throw new NullPointerException();
}
catch(ReportException e){
}
对我来说,NullPointerException 是从 Exception 类派生的,我的自定义 ReportException 也是如此,因此我希望它可以在 catch 子句中捕获。但是我的 IDE 说这是非法的。我和我的一位同事讨论过这个问题,他说不能这样做,但我只是想知道为什么,因为它们都来自同一个 Exception 类。这看起来违背了多态性。
【问题讨论】:
-
"...NullPointerException is derived from Exception class and so is my custom ReportException so since there the same type..."-- 狗是动物,猫也是,但这并不意味着狗是猫。 -
NullPointerException和ReportException都是Exceptions,但NullPointerException不是ReportException的一种。同理,德国人和意大利人都是欧洲人,但德国人不是意大利人。 -
@immibis 错误。 Polymorphism. 顺便说一下,这个问题实际上是关于什么的。
标签: java exception inheritance exception-handling polymorphism