访问自定义例外中的字段时出现问题



我创建了一个带有用户定义字段的自定义异常。我有一个 catch 块,我正在尝试访问用户定义字段中的值,但该值始终为 0。不知道出了什么问题。代码如下,

public class CustomException extends Exception
{
private int index;
public CustomException() {
super();
}
public CustomException(String message, int index) {
super(message);
this.index = index;
}
public int getIndex() {
return index;
}
}

我正在访问自定义异常的用户定义字段的代码,

try {
// Call another class's method that throws the CustomException
ExceptionDemoClass demoClass = new ExceptionDemoClass();
demoClass.demoMethod();
} catch (CustomException ex) {
System.out.println("Index is " + ex.getIndex());
}
public class ExceptionDemoClass {
public void demoMethod() throws CustomException {
throw new CustomException("Issue with code ", 1);
}
}

这里有几件事在起作用。我们将一一看它们。

在问题的第一次修订中,有这样一行代码:

System.out.println("Index is ", + ex.getIndex);

调用ex.getIndex缺少括号()。此外,需要删除"Index is "后面的逗号。

在第三个版本中,调用CustomException构造函数中的super(id);会导致编译错误,因为Exception中不存在这样的构造函数。

所有这些错误都在第五版中得到了修复。此代码按原样工作正常(Ideone 演示(。它甚至在第六版中继续工作(与第七版基本相同,只是格式发生了变化(。

最新更新