AgostinoX
AgostinoX

Reputation: 7683

java exceptions preserve encapsulation example

I have a class that manages a file on disk, saving a reoport in the form of xml. Since it uses JAXB (but could use any other xml library, it's not relevant) it could generate jaxb (or anyother xml library) checked exceptions.
In order to preserve encapsulation, I should "convert" my original-library exception in something at the logical level of my library. But I not want to increase much the number of classes with little, poorly relevant classes. Since the class is file-related, i think that IOException is adequate for the case.

public void save(File file) throws IOException {
    try{
        JAXBContext jc = JAXBContext.newInstance(ArchiveInfo.class);
        Marshaller m = jc.createMarshaller();
        m.marshal(this, file);
    } catch (JAXBException jexc) {
        throw new IOException(jexc);
    }
}
  1. Do you agree with this solution, is a good trade-off between simplicity and correctness?
  2. I've been lucky, because i found a suitable exception. If I wasn't, I would necessarily define my own exception, because using Exception class isn't good desing. (Causes the caller to catch Exception, catching implicitly also RuntimeException). Isn't it an anomaly in the structure of exceptions that runtime exceptions have a common ancestor in RuntimeException class, while all checked exceptions haven't?

Upvotes: 1

Views: 2330

Answers (1)

solendil
solendil

Reputation: 8468

1) I agree with you and tend to do the same: manually keeping lots of exception types is useless most of the time. All you need at the higher levels of the app is sufficient precision to be able to provide a meaningful error to the user. In your case "File could not be read", hence IOException is OK.

2) Yes it is a long-documented flaw of the Exception mechanism in Java... Some would even say the Exceptions mechanism in Java is flawed at its root (checked exceptions are misused most of the time). Anyway in your case, I sometimes use the catch-it-all InvalidStateException or IllegalArgumentException. Of course you can always create your own exceptions if you need more precise meaning to be conveyed to upper layers of your app. But remember : KISS :)

Upvotes: 2

Related Questions