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

JavaExceptionInheritance

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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);
    }
}

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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."

Solution 5 - Java

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());
        }
    }
}

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyegor256View Question on Stackoverflow
Solution 1 - JavadjnaView Answer on Stackoverflow
Solution 2 - JavanandaView Answer on Stackoverflow
Solution 3 - JavaKevin BreyView Answer on Stackoverflow
Solution 4 - JavaIsaqView Answer on Stackoverflow
Solution 5 - JavaDeepak PakhaleView Answer on Stackoverflow
Solution 6 - JavaDeepak PakhaleView Answer on Stackoverflow
Solution 7 - JavavulkaninoView Answer on Stackoverflow
Solution 8 - JavaLorne KView Answer on Stackoverflow