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?
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.
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.
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.
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.
Return false
.
Exception is EXCEPTION, and should be thrown in exceptional cases only, when script can't continue execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With