javadesign-patternsexception

How to inherit a RuntimeException class?


I have two options:

public class SyntaxException extends RuntimeException {
  private String msg;
  public SyntaxException(String m) {
    this.msg = m;
  }
  public String getMessage() {
    return "Invalid syntax: " + this.msg;
  }
}

and

public class SyntaxException extends RuntimeException {
  public SyntaxException(String m) {
    super("Invalid syntax: " + m);
  }
}

Which one is preferred, if I have to think about code maintainability and extendability?


Solution

  • Use the second one. The argument to the constructor of both RuntimeException and your inherited class is the error message, so there's no reason to duplicate that functionality already given by RuntimeException in your code.