Thanks, I think I'm getting it now. Is this a good case for exception handling?
- If can't connect to database, throw exception
- If can't select database, throw exception
- If can't set charset, throw exception
Try all three and perform only a single catch. Given that I regard all three are enough to kill the script I simply log the error message, code, line number, etc to a file and display a “The database is currently down, please come back later” type message.
My second example, is not one that kills the script. I am trying to write to a file that should already exist.
- If the file does not exist, throw exception
- If the file is not writable, throw exception
Again, I only need to catch it once so the code is tidier than if/else. In each case, I can display an error message and insert it into an unwritable database and carry on as usual.
Are these both good use cases?
So from what I can see so far exceptions are good because:
- You can add lots of exceptions in your code and only catch once
- You can catch anytime between it getting thrown and the end of the script
- The Exception class allows you to create custom error codes/message and get the trace/file/line
- You can extend the Exception class for more customised error reporting
And it shouldn't be used for general validation (form validation, numbers being out of range, etc).
Finally, is set_error_handler() a good idea? Seem a bit lazy in a global kind of way.
I guess also, if you have a bootstrap there might be loads of things that could generate an error that warrants killing the script and you could do it all in a single try/catch.