Java checked exceptions: how do i solve this?
Hi,
One of my biggest troubles is how to sort out java checked exceptions.
I'd like to understand how to "correctly" implement them when
"delegating" roles.
Here i will explain an example in detail.
I am developing the class Node that represents a node of a tree: it
has the possibility to load its children lazily after setting its
ChildrenLoadingStrategy. The core methods in this class are
getChildren() and getFather().
public abstract class Node {
private ChildrenLoadingStrategy strategy = null;
public setChildrenLoadingStrategy(ChildrenLoadingStrategy strategy) {
this.strategy = strategy;
}
public List<Node> getChildren() {
if (strategy != null) {
strategy.loadChildren(this);
}
}
public void addChild(Node childNode) {...}
protected void setFather(Node nodeFather) { //this method is called
by addChild() }
public Node getFather() {...}
public List<Node> getBrothers() {...}
[*] plus lots of other methods that contains calls to getChildren()
}
interface ChildrenLoadingStrategy {
void loadChildren(Node node); //calls node.addChild()
}
Briefly: The Node class delegates getChildren() to the
ChildrenLoadingStrategy. Maybe this is not "strictly" exact, probably
the design is not perfect, but it's just an example.
Suppose that the an implementation of
ChildrenLoadingStrategy.loadChildren() contains SQL code. And
SQLExceptions.
Suppose that the another implementation of
ChildrenLoadingStrategy.loadChildren() contains I/O code. And
IOExceptions.
How do i reflect these exceptions in the Node.getChildren() method?
Solution 1: declare a brand new Exception that encanpsulates the inner
ones.
void loadChildren(Node node) throws ChildrenLoadingException {
try {
...
} catch(Exception e) {
throws ChildrenLoadingException(e);
}
}
public List<Node> getChildren() throws ChildrenLoadingException {...}
public List<Node> anyOtherMethodInNodeThatCallsGetChildren() throws
ChildrenLoadingException {...}
Comment: Do you like it? i don't. Somehow it "stinks"
Solution 2: declare ANY Exception
void loadChildren(Node node) throws Exception {...}
public List<Node> getChildren() throws Exception {...}
public List<Node> anyOtherMethodInNodeThatCallsGetChildren() throws
Exception {...}
Comment: mmmmm.
Solution 3: say goodbye to checked exceptions
void loadChildren(Node node) {
try {
...
} catch(Exception e) {
throws new RuntimeException(e);
}
}
public List<Node> getChildren() {...}
public List<Node> anyOtherMethodInNodeThatCallsGetChildren() {...}
Comment: Terrific! Or maybe better than solution 2?
What can you suggest me about solution 1, 2 or 3?
Have u got any other solution?
Thank you very much