我是否应该为每种验证创建专门的异常,例如:
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");
...
}
或者,我应该做一个通用异常,例如:
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");
...
}
最佳答案
如果使用第一种方法,那么调用者可以单独处理每个异常:
try
{
doSomething(new Text("blah blah"));
}
catch(NonAlphaNumericException e){/* do something */}
catch(BlankException e){/* do something else */}
关于java - Java 中 validator 异常的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17954936/