When to use exception handling for website
I've been reading about exception handling in PHP. The logic of it looks very simple yet I'm confused as to when/how to use it in a website context. From what I can see the advantages are:
- Throwing multiple exceptions results in more concise code compared to loads of if/elses
- A thrown exception can be caught outside of the function that threw it
- You can throw multiple exceptions and only need to catch it once (though you don't have to)
- It makes use of internal PHP error reporting functionality since you can set error codes and messages and get file, line and trace
- You can extend the Exception class
However, it seems to be there is little need for this in a website. I can see in a standard desktop application that is running constantly exceptions need to be handled and dealt with. Let's say I connect to a database and program it so separate exceptions are thrown for 1. Can't connect, 2. Can't set charset, 3. Can't select database
If any of these exceptions occur, the website is (usually) useless anyway so why not just do some error logging then and exit() or die()?
A few further questions:
- In a website, when should it be used? Surely it is not meant for validation. For example, if I am expecting a page number as a GET var, aren't I better off casting it as an int and then checking it is not negative?
- If the script cannot continue due to a certain exception (e.g. database error as above), should you leave the exception uncaught so it stops the script? (And perform any error logging via set_exception_handler)
- Is there ever a need to use exception handling with set_error_handler?
Can someone please help clarify this? Thanks.