Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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?

1 Answer

0 votes
by (46k points)

Nope, you don't "obtain" non-default constructors, you require to determine the one using a String in your class. Typically you practice super(message) in your constructor to request your parent constructor. For instance, like this:

public class MyException extends Exception {

    public MyException(String message) {

        super(message);

    }

}

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...