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

Time:05-26

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.

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

CodePudding user response:

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");
    }
}
  • Related