Joan said:
I am reading a file and checking each piece of data.
If there is something wrong with the data, I do this:
throw new IOException("Cell type not NUMBER at row = " + ix........");
How does one decide if this is the sort of thing that
should have it's own Exception like BadDataException() ?
The main problem for reusing rather than creating new exception classes,
comes when we need to handle the exceptions differently.
For example, how would the calling code be able to differentiate between
the IOException stated above, and any other IOException - like
FileNotFoundException, etc. ?
By reusing a single exception type for multiple reasons, we lose the
class type differences, which prevents having specific catch blocks and
so specific handlers.
Just today, I was developing a Model class that data could be
Added/Edited/Removed from.
The model throws exceptions when:
1) adding of data if the identifier has already been used,
2) editing data when the identifier does not exist.
3) Removing data when the identifier does not exist.
all three methods throw specific kinds of exceptions to show the intent
of their interface, rather than a generic ModelException. However, all
exceptions do extend an Abstract ModelException, so callers have a
choice of handling the explicit exception from each method, or just the
generic intermediate class.
for example...
class Model {
void add(Id id, Object data) throws IdentifierAlreadyExistsException {
if (contents.containsKey(id)){
throw new IdentifierAlreadyExistsException (id);
}
...
}
void edit(Id id, Object data) throws NonExistantIdentifierException {
if (! contents.containsKey(id)){
throw new NonExistantIdentifierException (id);
}
}
...
}
class abstract ModelException extends Exception (
ModelException(ID id, String message) {
super(message);
this.id = id;
}
Id getId() {
return id;
}
private Id id;
}
class NonExistantIdentifierException extends ModelException {
NonExistantIdentifierException(Id id) {
super(id, "no data for the supplied Identifier exists");
}
}
class IdentifierAlreadyExistsException extends ModelException {
IdentifierAlreadyExistsException(Id id) {
super(id, "data for the supplied Identifier already Exists");
}
}