简体   繁体   English

Java中用户定义的异常的编码样式

[英]Coding Style for User defined Exception in java

I'm working on a java project. 我正在研究Java项目。 while browsing the existing code of User defined Exception class, i came across a the code written like below: 浏览用户定义的Exception类的现有代码时,我遇到了如下所示的代码:

public final class ApplicationException extends RuntimeException {

public static void enforce(final String message) {
    throw new ApplicationException(message);
}
private ApplicationException(final String message) {
    super(message);
}
}

and whenever i have to throw an exception within code, I write 每当我必须在代码内引发异常时,我都会写

ApplicationException.enforce("exception message here");

I wanted to know is this some coding style or pattern ie enclosing the creation and throw of Exception in a public static method and calling that method whenever we want to throw exception? 我想知道这是某种编码样式或模式,即将Exception的创建和抛出封装在公共静态方法中,并在我们每次抛出异常时调用该方法吗?

What may be the reason developer chose this way to throw exception? 开发人员选择这种方式引发异常的原因可能是什么? why not directly write throw new ApplicationException("some message"); 为什么不直接写throw new ApplicationException("some message"); whenever required. 必要时。

what is the gain using that style? 使用该样式有什么好处?

Thanks in advance 提前致谢

I don't think there are any specific reason for it and the pattern is not commonly used in Java projects. 我认为没有任何具体原因,并且该模式在Java项目中并不常用。

He probably just used such code to look nicely. 他可能只是用这样的代码来看起来不错。

It encapsulates the new keyword in a method, which might be seen as making the user-defined exception into a kind of simple factory . 它将new关键字封装在一个方法中,这可以看作是将用户定义的异常变成一种简单的factory

This might have advantages for maintenance and/or testing later, since you just change the implementation of the enforce method and client code calling it will change. 这可能在以后的维护和/或测试中具有优势,因为您只需更改enforce方法的实现,并且调用该方法的客户端代码也会更改。

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

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