简体   繁体   English

如果未注入属性,抛出的异常类型是什么?

[英]What is type of exception to throw if property is not injected?

If module was not injected, in methodA which type of exception can i throw? 如果未注入模块,则可以在methodA中抛出哪种类型的异常?

 public class Customer{
       private String module;

       public void methodA(){
         if (StringUtils.isBlank(module))
           throw new ???
       }
    }

You can either create your own custom exception, or throw IllegalStateException along with an appropriate message. 您可以创建自己的自定义异常,也可以抛出IllegalStateException以及适当的消息。 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 . 换句话说, 对于所请求的操作Java环境或Java应用程序未处于适当的状态 (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. 由于您不希望module为空,因此您处于无效状态,因此在这种情况下,将IMO抛出此异常是合适的。

No Specfic predefined Exception is already there which you can make use of. 还没有可以使用的Specfic预定义Exception So you can make a new one like ModuleException :- 因此,您可以制作一个新的模块,例如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:- 创建ModuleException您可以将其抛出到类中:

public void methodA(){
         if (StringUtils.isBlank(module))
           throw new ModuleException("Module is blank but is MANDATORY");
       }

I would've said to use NullPointerException but the isBlank method also returns true when it's an empty String. 我会说要使用NullPointerException但是当isBlank方法为空String时,它也会返回true The best option would probably be to make your own Exception (info can be found here ). 最好的选择可能是使自己的异常(信息可以在这里找到)。 That way you also get complete customization. 这样,您还可以获得完全的自定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM