helpermethod
helpermethod

Reputation: 62165

Creating a new Exception type - write all constructors or only those needed?

When I write a new exception type, am I supposed to write only the constructors needed, or implement all constructors exisiting in Throwable (and calling them by super())?

When thinking about it, I would say implement only what is needed (YAGNI - You Ain't Gonna Need It). If I need another constructor later, I just add it.

Example:

public void MyException extends RuntimeException {
    // I only need this constructor
    public MyException(Throwable cause) {
        super(cause);
    }
}

Upvotes: 1

Views: 512

Answers (3)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

It depends what you are writing for.

For a small program, do not write dead code.

If the class is going into a library or will be used by other team/team-members where there is some kind of code ownership going on, then write the complete class. Be careful with this: "speculative generalisation" is a serious problem in software development.

Upvotes: 2

ThiagoUriel
ThiagoUriel

Reputation: 115

Yes, you should implement just the ones you are going to need.

Systems around that I work/worked wich, usually implements at least a constructor that receives the exception cause (exactly like your example). Also an exception defining only a default constructor won't do make much sense unless it's something very very very specific.

Best regards.

Upvotes: 1

Jaco Van Niekerk
Jaco Van Niekerk

Reputation: 4182

Only implement what you'll need and add as you need them. I usually add the one with the String message and the one you have (for wrapping another Exception).

Upvotes: 3

Related Questions