2

I made an exception to show what's the cause of error.

below is my code

public class DefaultException extends RuntimeException {

    /**
     * DefaultException
     */
    private static final long serialVersionUID = 1L;


    /**
     * Constructor
     * @param cause exception
     */
    public DefaultException(Exception cause) {
        super(cause) ;
    }

    /**
     * Constructor
     * @param cause error message
     */
    public DefaultException(String message) {
        super(message) ;
    }

    /**
     * Constructor
     * @param cause message, exception
     */
    public DefaultException(String message, Throwable cause) {
        super(message, cause) ;
    }
}

Generating one of these constructors, specifying what's the error is successfully done.

But I want to return an error code additionally there.

It looks like...

public DefaultException(String message, String errorCode) {
    super(message, errorCode) ;
}

But Throwable class doens't have that constructor, so this can't be acheived this way.

How can I do this?

1
  • Create a custom field with this errorcode Commented Aug 5, 2014 at 0:11

1 Answer 1

8

Put the errorCode into a field that the DefaultException has and then when you catch a DefaultException, call getters to retrieve it.

public class DefaultException extends RuntimeException {

    private String errorCode;

    public DefaultException(String message, String errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public String getErrorCode() {
        return errorCode;
    }

    // ...
}

Then when you catch it you can go like this:

    try {
        //something that will error
    } catch (DefaultException e) {
        String errorCode = e.getErrorCode();
        // ...
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.