andolffer.joseph
andolffer.joseph

Reputation: 613

What is the best approach for Validator Exceptions in Java?

Should I create a specialized Exception for each kind of validation, for sample:

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");
   ...
}

Upvotes: 0

Views: 75

Answers (2)

Pierpaolo Cira
Pierpaolo Cira

Reputation: 1477

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.

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...).

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117587

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 */}

Upvotes: 3

Related Questions