289

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?

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34
yegor256
  • 102,010
  • 123
  • 446
  • 597

8 Answers8

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);
    }
}
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
djna
  • 54,992
  • 14
  • 74
  • 117
  • the default constructor IS inherited. – vulkanino Sep 23 '10 at 07:55
  • 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. – Michael Borgwardt Sep 23 '10 at 08: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. – Sean Patrick Floyd Sep 23 '10 at 08:39
  • 44
    Please add the `MyException(Throwable)` and `MyException(String, Throwable)` constructors to properly support [exceptions chaining](http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html). – Danilo Piazzalunga Sep 18 '13 at 13:13
  • 8
    Nearly 3 years later and none of the extra constructors have been added. :( – byxor Sep 01 '16 at 09:00
  • 1
    @Brandon Ibbotson anyone who cares to do so is free to add them; in my view they are not germane to the original question, but I have no objections to anyone editing my answer. – djna Sep 01 '16 at 10:15
  • @djna I agree, plus they're implicitly added anyway so it wouldn't make any difference. – byxor Sep 01 '16 at 10:17
  • 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 Nov 01 '16 at 11:28
  • @halil That is definitely not what I meant. I admit that my comment could have made you think that way. By **"implicitly added"** I just meant that you can invoke the `Exception` constructors _as if_ they were already added to the `MyException` class, even if `MyException` has not overridden them. – byxor Nov 02 '16 at 00:55
  • why do you say "non-default" c'tor? – rooni Nov 12 '18 at 08:24
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.

nanda
  • 24,458
  • 13
  • 71
  • 90
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.

Kevin Brey
  • 1,233
  • 1
  • 12
  • 18
  • 1
    Why is it not necessary for the default constructor to call `super()`? – ceving Oct 15 '14 at 12:42
  • 4
    ["If the subclass constructor does not specify which superclass constructor to invoke then the compiler will automatically call the accessible no-args constructor in the superclass."](http://stackoverflow.com/a/2054040/2437516) – Kevin Brey Dec 24 '14 at 18:16
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."

Tony Rad
  • 2,479
  • 20
  • 32
Isaq
  • 259
  • 2
  • 4
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());
        }
    }
}
mattumotu
  • 1,436
  • 2
  • 14
  • 35
Deepak Pakhale
  • 219
  • 2
  • 2
  • what would this return? – user1876508 Aug 21 '13 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 Jul 18 '14 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.
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75
Deepak Pakhale
  • 219
  • 2
  • 2
  • 3
    Actually, since Java 1.4, there are two more constructors: `public Exception(Throwable)` and `public Exception(String, Throwable)`. They are needed to properly support [exceptions chaining](http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html). – Danilo Piazzalunga Sep 18 '13 at 13:12
  • @DaniloPiazzalunga agree with you . source : Constructor Summary http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Exception.html – KNU May 27 '14 at 05:53
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).

vulkanino
  • 9,074
  • 7
  • 44
  • 71
  • I think you should add reason also. – jmj Sep 23 '10 at 08: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 Sep 23 '10 at 08: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");
Lorne K
  • 109
  • 7