Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation Class - should return false or throw exception?

Tags:

php

I am creating a class that validates strings. There are many reasons why the string might not pass.

Would it make more sense to throw an exception, or return false/error code? Pros/cons?

like image 548
Andy Hin Avatar asked May 25 '11 20:05

Andy Hin


People also ask

Should validation methods throw exception?

Notice how none of the validation methods throw exceptions. Rather they return true or false. There is no need to throw an exception even if the input data is invalid. In contrast, inside a DAO class you will most likely not be able to interact with the user to correct the error.

Is validation error an exception?

A ValidationException is thrown if a validation error occurs. The exception is thrown when the Validate method is called. All the exceptions that are thrown during validation are contained in the InnerExceptions collection. You can retrieve each validation exception by iterating through the InnerExceptions collection.

What is the difference between exception and validation?

Data validation means checking the data before performing operations that could fail, for example check for 0 before doing a division. Exception handling means well defined behavior if an operation fail, for example if a database query times out.


2 Answers

validators should not throw exceptions, as failing a validator is not an "exceptional" event.

the rest of your code should throw exceptions if it gets bad data.

when you run a validator function you are clearly prepared to handle any problems detected with a simple test. wrapping everything in a try/catch block and stopping all execution only to try to recover is overkill. Just use and if statement, and be prepared to show the user some error messages.

like image 171
David Chan Avatar answered Sep 22 '22 07:09

David Chan


Return false.
Exception is EXCEPTION, and should be thrown in exceptional cases only, when script can't continue execution.

like image 44
OZ_ Avatar answered Sep 22 '22 07:09

OZ_