j2e*_*nue 1 java polymorphism inheritance exception-handling exception
请检查下面的自定义例外:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么在另一堂课中这是非法的:
try{
throw new NullPointerException();
}
catch(ReportException e){
}
Run Code Online (Sandbox Code Playgroud)
对我来说,NullPointerException是从Exception类派生的,因此我的自定义ReportException也是如此,因为我希望它可以在catch子句中捕获.但我的IDE说这是非法的.我与我的一位同事进行了这次讨论,他说那里无法完成,但我只是想知道为什么因为它们都来自同一个Exception类.这看起来无视多态性.
A NullPointerException和你们ReportException都是Exceptions,但要抓住一个ReportException,你必须抛出一个ReportException(或一个子类).A NullPointerException不是ReportException它的子类,因此它没有被捕获.
扔一个ReportException而不是.
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |