Java 访问自定义异常中的字段时出现问题
我用用户定义的字段创建了一个自定义异常。我有一个catch块,试图访问用户定义字段中的值,但该值始终为0。不知道怎么了。代码如下:Java 访问自定义异常中的字段时出现问题,java,exception,Java,Exception,我用用户定义的字段创建了一个自定义异常。我有一个catch块,试图访问用户定义字段中的值,但该值始终为0。不知道怎么了。代码如下: public class CustomException extends Exception { private int index; public CustomException() { super(); } public CustomException(String message, int index) {
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
缺少括号()
。此外,“索引”后面的逗号是“
”需要删除
在调用super(id)的过程中CustomException
的构造函数中的code>将导致编译错误,因为该构造函数在中不存在
所有这些错误都已在中修复。这段代码可以正常工作()。它甚至可以在中继续工作(与基本相同,只是更改了格式)。此代码现在打印“索引为1”,因此我想您可以删除您的问题。在原始代码中,异常是在不同的类中抛出的,而不是处理的类,并且它不是打印1。然后发布一个完整的最小示例,实际再现该问题。你发布的代码没有。仍然有效…如果你提供一个,我将很高兴地看一看,并修改我的答案。但是,照目前的情况,我看不出当前版本的代码有任何问题。既不是从理论角度,也不是从实践角度(作为我的证明)。但话说回来,提供一个非功能性的,我会很乐意接受我自己的话。