Search code examples
javaexceptionoverriding

getMessage() without overriding in Exception


I have a class which extends Exception, but I am not allowed to override getMessage() from Exception so I got to find a way around it.

Just for a visualisation of the task, here is a example:

public class NoCertificateException extends Exception {

    private Student[] students;

public NoCertificateException(Student[] students) {
        this.students = students;

public String getMessage() {
        String arrayToString = Arrays.toString(students);
        String s =  " has/have no certificate(s)";
        return arrayToString + s;
}

but in this case getMessage() gets overriden


Solution

  • Exception has a constructor which takes a string, which is then used as the message.

    So, invoke that constructor inside your constructor:

    public NoCertificateException(Student[] students) {
      super(Arrays.toString(students) + " has/have no certificate(s)");
    }