How to define custom exception class in Java, the easiest way?

yegor256 picture yegor256 · Sep 23, 2010 · Viewed 404.8k times · Source

I'm trying to define my own exception class the easiest way, and this is what I'm getting:

public class MyException extends Exception {}

public class Foo {
  public bar() throws MyException {
    throw new MyException("try again please");
  }
}

This is what Java compiler says:

cannot find symbol: constructor MyException(java.lang.String)

I had a feeling that this constructor has to be inherited from java.lang.Exception, isn't it?

Answer

djna picture djna · Sep 23, 2010

No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}