I'm creating a custom exception to parse a specific file format. The base class is FileFormatException
(I've replaced the name of the file format with FileFormat
). It has a constructor public FileFormatException(String filepath)
that will output a generic error message, such as "Error parsing <filepath>".
Now, the difficulty occurs when I try and create subclasses for more specific errors. These subclasses would have their own error messages, which requires a method such as public FileFormatException(String message)
. But this is not possible, as it conflicts with the first constructor (they both have the same parameters).
I tried to solve the issue by having a protected setMessage
method in FileFormatException
, which the subclasses can call, but this won't work, as Java does not allow setting attributes before calling super()
.
I have a working solution as well, but it very rigid. When a subclass is invoked, I'm forced to include the default message every time with the subclass's custom message.
The constraints are:
FileFormatException
super(message)
, since Exception
does not have a setter for the message.I feel like Java is forcing me into a weird corner, since Exceptions don't have setters.
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();
}
}
Just use File
or preferably Path
for any file system paths, and then there is no ambiguity about whether you mean a message or a file
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);
}