I am working on a pretty large project and have read a lot about exception here at stackoverflow and on other websites. The result was, that there is 100% right or wrong. Some throw exceptions for unvalid user inputs, some don’t. Some throw exceptions only for runtime errors, some don’t…
I personally like the way to throw exceptions even for unvalid user inputs.
Now my problem is that I have for example a user that can comment on a statement of another user (for example his/her favorit music and so on). Every user is only allowed once to comment on it. Now the function which creates a database entry for the comment, checks whether the user has already commented on that statement.
If yes, throw an exception. Normally I would say that I name this exception: ExceptionStatementAlreadyCommented
but I have many other functions in this project and if I always create such specific exceptions I would end up with about 100 – 200 exceptions.
Does this affect the performance? I autoload the classes needed via the __autoload function, so the actual exception is only loaded when it is needed.
Is it a good way to name exceptions like this?
In the past I had trouble with using one exception for different errors because when I catched the exceptions, I sometimes catch exception that I did not want to catch.
Thank you really much for your help!
Best regards,
Freddy
It’s good to have a tree of exceptions, extending from the most general to the most specific, for instance, your
StatementAlreadyCommentedException(That’s how it should be named, with the Exception part at the end) should inherit fromInvalidUserInputException, or maybeAlreadyExistsExceptionexception, and those should inherit from something more general, likeException.This way, you can catch all exceptions more specific than the one you’re searching (should you ever need it). (You can catch
Exception, and it would catch every possible exception, you can catchAlreadyExistsExceptionand it would catch any exception extending it.