0

If module was not injected, in methodA which type of exception can i throw?

 public class Customer{
       private String module;

       public void methodA(){
         if (StringUtils.isBlank(module))
           throw new ???
       }
    }
Fariba
  • 693
  • 1
  • 12
  • 27

3 Answers3

1

You can either create your own custom exception, or throw IllegalStateException along with an appropriate message. From the docs:

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. (emphasis mine)

Since you don't expect module to be blank, you're in an invalid state and hence this exception would be appropriate to throw in this case IMO.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0

No Specfic predefined Exception is already there which you can make use of. So you can make a new one like ModuleException:-

public class ModuleException extends Exception {
  public ModuleException() { super(); }
  public ModuleException(String message) { super(message); }
  public ModuleException(String message, Throwable cause) { super(message, cause); }
  public ModuleException(Throwable cause) { super(cause); }
}

After creating ModuleException you can throw it in your class like:-

public void methodA(){
         if (StringUtils.isBlank(module))
           throw new ModuleException("Module is blank but is MANDATORY");
       }
AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
0

I would've said to use NullPointerException but the isBlank method also returns true when it's an empty String. The best option would probably be to make your own Exception (info can be found here). That way you also get complete customization.

Community
  • 1
  • 1
cbender
  • 2,231
  • 1
  • 14
  • 18