[英]What is the best approach for Validator Exceptions in Java?
Should I create a specialized Exception for each kind of validation, for sample: 我应该为每种验证创建专门的Exception,例如:
public void doSomething(Text text) {
if (!text.isAlphaNumeric()) throw new NonAlphaNumericException("Text should be alphanumeric");
if (text.isBlank()) throw new BlankException("Text should not be empty or null");
...
}
or, should I do a generic exception like: 或者,我应该做一个通用异常,例如:
public void doSomething(Text text) {
if (!text.isAlphaNumeric()) throw new TextValidationException("Text should be alphanumeric");
if (text.isBlank()) throw new TextValidationException("Text should not be empty or null");
...
}
If you use the first approach, then the caller can handle each exception separately: 如果使用第一种方法,则调用者可以分别处理每个异常:
try
{
doSomething(new Text("blah blah"));
}
catch(NonAlphaNumericException e){/* do something */}
catch(BlankException e){/* do something else */}
It depends by what you need to do with these exceptions. 这取决于您需要如何处理这些异常。
Another way is to use an Hybrid approach: you create a main ExceptionType and some derived exceptions. 另一种方法是使用混合方法:创建一个主要的ExceptionType和一些派生的异常。
In this manner you Can choose what exception you want to raise/manage in a specific way. 通过这种方式,您可以选择要以特定方式引发/管理的异常。 The others Can be managed in more general way.
其他可以通过更一般的方式进行管理。
It sounds like the difference between java.lang.Exception and other subtypes (eg. IOException etc...). 听起来像java.lang.Exception和其他子类型(例如IOException等)之间的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.