290

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?

8 Answers 8

405

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);
    }
}
10
  • 58
    @vulkanino: No. The default constructor is added by the compiler for every class that defines no constructor of its own. If you define an explicit constructor, you don't get the default even if the superclass has it, and if your class has no constructor, you get the default even if the superclass does not have it. Commented Sep 23, 2010 at 8:10
  • 5
    if your class has no constructor, you get the default even if the superclass does not have it The last part is impossible, unless the superclass has a default constructor that is accessible to this class (may be protected or package-protected). Otherwise you must explicitly call one of the parent constructors, or compilation will fail. Commented Sep 23, 2010 at 8:39
  • 44
    Please add the MyException(Throwable) and MyException(String, Throwable) constructors to properly support exceptions chaining. Commented Sep 18, 2013 at 13:13
  • 8
    Nearly 3 years later and none of the extra constructors have been added. :(
    – byxor
    Commented Sep 1, 2016 at 9:00
  • 2
    @BrandonIbbotson What do you mean by 'they', and where are they added? If what you meant by 'they' are superclass constructors and by 'where' is subclass, then you are wrong. Superclass constructors are not implicitly added to subclass. Plus I can't see any other subject in the previous sentences for those words to refer.
    – halil
    Commented Nov 1, 2016 at 11:28
90

A typical custom exception I'd define is something like this:

public class CustomException extends Exception {

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable throwable) {
        super(message, throwable);
    }

}

I even create a template using Eclipse so I don't have to write all the stuff over and over again.

2
  • 17
    You can just extend Exception when creating your Class in Eclipse and you'll get all four constructors. You don't need a template. Commented Jan 9, 2014 at 3:41
  • When should we use the second Consutructor instead of the first one?
    – ZhaoGang
    Commented Nov 14, 2019 at 7:24
62

If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception and check "Constructors from superclass" and it will generate the following:

package com.example.exception;

public class MyException extends Exception {

    public MyException() {
        // TODO Auto-generated constructor stub
    }

    public MyException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public MyException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}

In response to the question below about not calling super() in the defualt constructor, Oracle has this to say:

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

2
22

Reason for this is explained in the Inheritance article of the Java Platform which says:

"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."

19
package customExceptions;

public class MyException extends Exception{

    public MyException(String exc)
    {
        super(exc);
    }
    public String getMessage()
    {
        return super.getMessage();
    }
}

import customExceptions.MyException;

public class UseCustomException {

    MyException newExc=new MyException("This is a custom exception");

    public UseCustomException() throws MyException
    {
        System.out.println("Hello Back Again with custom exception");
        throw newExc;       
}

    public static void main(String args[])
    {
        try
        {
            UseCustomException use=new UseCustomException();
        }
        catch(MyException myEx)
        {
            System.out.println("This is my custom exception:" + myEx.getMessage());
        }
    }
}
2
  • what would this return? Commented Aug 21, 2013 at 17:52
  • It would just print out "Hello Back Again with custom exception" which is from the constructor for UseCusomException, the exception would be thrown then caught in the main which would print out "This is my custom exception:This is a custom exception".
    – ThePerson
    Commented Jul 18, 2014 at 13:11
2

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.
2
0

If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).

2
  • I think you should add reason also. Commented Sep 23, 2010 at 8:08
  • 3
    actually, that is incorrect. If your code uses a constructor with one String argument, then you have to declare it. However, an Exception subclass can be defined with no explicit constructors ... because Exception has a no-args constructor.
    – Stephen C
    Commented Sep 23, 2010 at 8:26
0

and don't forget the easiest way to throw an exception (you don't need to create a class)

if (rgb > MAX) throw new RuntimeException("max color exceeded");

Not the answer you're looking for? Browse other questions tagged or ask your own question.