Search code examples
javaconstructorsuperclass

super class constructor in custom exception in java


I am learning features in java including exceptions. I am writing a custom exceptions. Here is what i am doing :custom exception class:

 public class ServiceException extends Exception {

    private String customMessage;

    public ServiceException(String customMessage) {
        super(customMessage);
        this.customMessage = customMessage;

    }
}

Main class:

    public class Main {

    public static void main(String[] args) {
        try {
            new Main().test();
        } catch (Exception e) {
            System.out.println("the exception message is " + e.getMessage());
        }
    }

    public void test() throws ServiceException {
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}

This much i know: if super class constructor is not invoked in the custom exception class, the message set in the custom exception is not passed to the Exception class. But if i have a method public String getMessage in my custom exception class, even if the super is not invoked, that message is printed . Sorry if this is a naive question. But i am failing to understand he concept. Could come one help clear the concept ?


Solution

  • In main where you are catching the error, you are basically assigning a ServiceException object to a Exception reference, i.e. assigning derived class object to base class reference, so if the derived class has overridden the method, it will get called.

    the e.message() being called is from ServiceException not Exception, you are right, no data is being passed when you are not calling super, data is inside ServiceException class only and the function invoked is also from ServiceException class.