This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: What is the easiest way to customize an exception class in Java?

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(a) throws MyException {
    throw new MyException("try again please"); }}Copy the code

This is what the Java compiler shows:

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

I feel like this constructor should be inherited from the java.lang.Exception class, right?

Answer a

No, you cannot “inherit” non-default constructors; you need to define constructors in your class that take a String argument. Usually you use super(message) in your constructor to call the parent constructor. For example, something like this:

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

Answer two

package customExceptions;

public class MyException extends Exception{

    public MyException(String exc)
    {
        super(exc);
    }
    public String getMessage(a)
    {
        return super.getMessage(); }}Copy the code
import customExceptions.MyException;

public class UseCustomException {

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

    public UseCustomException(a) 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()); }}}Copy the code

Answer three

If you use the new class dialog in Eclipse, you can set the Superclass property to java.lang.Exception and check “Constructors from Superclass”, which will generate the following:

package com.example.exception;

public class MyException extends Exception {

    public MyException(a) {
        // 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}}Copy the code

Answer four

If you inherit from the Exception class, you must provide a constructor that takes a String (which will contain an error message).

The article translated from Stack Overflow:stackoverflow.com/questions/3…