调用super之前需要设置属性

问题描述 投票:0回答:1

我正在创建一个自定义异常来解析特定的文件格式。基类是

FileFormatException
(我已将文件格式的名称替换为
FileFormat
)。它有一个构造函数
public FileFormatException(String filepath)
,它将输出通用错误消息,例如“错误解析 ”。

现在,当我尝试为更具体的错误创建子类时,就会出现困难。这些子类将有自己的错误消息,这需要诸如

public FileFormatException(String message)
之类的方法。但这是不可能的,因为它与第一个构造函数冲突(它们都有相同的参数)。

我尝试通过在

setMessage
中使用受保护的
FileFormatException
方法来解决这个问题,子类可以调用该方法,但这不起作用,因为 Java 不允许在调用
super()
之前设置属性。

我也有一个可行的解决方案,但它非常严格。当调用子类时,我每次都被迫在子类的自定义消息中包含默认消息。

限制是:

  • 子类必须继承自
    FileFormatException
  • 消息只能通过调用
    super(message)
    来设置,因为
    Exception
    没有消息的设置器。

我觉得 Java 将我逼入了一个奇怪的角落,因为异常没有 setter。

示例

public class FileFormatException extends Exception {
    public FileFormatException(String filepath) {
        super("Error parsing the file: " + filepath);
    }

    // This is prohibited in Java
    public FileFormatException(String message) {
        super(message);
    }
}

public class SpecificException extends FileFormatException {
    public SpecificException(String filepath) {
        super("Printing specific error message for: " + filepath);
    }
}

失败的尝试

public class FileFormatException extends Exception {
    private String message = null;

    public FileFormatException(String filepath) {
        super("Error parsing the file: " + filepath);
    }

    public FileFormatException() {
        if (message == null) { // This is probably not allowed either
            super();
        } else {
            super(message);
        }
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

public class SpecificException extends FileFormatException {
    public SpecificException(String filepath) {
        setMessage(message); // Java does not allow this
        super();
    }
}
java exception inheritance super
1个回答
0
投票

只需对任何文件系统路径使用

File
或最好使用
Path
,这样就不会不清楚您指的是消息还是文件

public FileFormatException(Path path) {
    super("Error parsing the file: " + path);
}
public FileFormatException(String message) {
    super(message);
}
...
public SpecificException(Path path) {
    super(path);
    // or
    super("Something else is wrong with: "+path);
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.