Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to have a different super(message) be displayed for a customException?

I have a custom exception class InvalidNameException that is supposed to handle an error if the input string either is too short or has any special characters.

I was wondering if it is possible to have a different super(message) be displayed based on what condition the input name satisfies.

It should ideally look like this but since super(message) needs to be the first message in a constructor, I am curious in knowing if this is something that can be done or do I need to find another way to achieve this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The customException class looks like this

    class InvalidNameException extends Exception
    {
      public InvalidNameException(String name)  {     
        if(validName(name)){  
         super("Name Contains Special Characters"); 
        }
        else if(validLength(name)){
         super("Name is too long");     
        }
      }
      public boolean validName(String name){
            boolean check = true;
            for (int i = 0; i < name.length(); i++) {        
                 if (!Character.isLetter(name.charAt(i))
                  && !Character.isWhitespace(name.charAt(i))) {               
                  check = false;
              }
          }
            return check;   
      }
      
      public boolean validLength(String name){
        boolean check = true;
        if(name.length()<6) {
            check = false;
        }
        return check;  
      }
    }

>Solution :

You cannot call super twice. To make this work, you would have to throw a new exception for each condition like this:

public InvalidNameException(String name) throws Exception {
    if(validName(name)){
        throw new Exception("Name Contains Special Characters");
    }
    else if(validLength(name)){
        throw new Exception("Name is too long");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading