I’m trying to understand exception handling in PHP and cant quite get it. I read every post, article and comment i could find, but cant seem to figure it out.
What i don’t understand is:
1. Why use exceptions?
Exceptions allow you to catch errors, if you think/know that an error could occur in a specific location in your code, then you can throw an exception and catch it.
What i don’t understand is why not set up the code to NOT be able to have an error in the first place? It kind of seems to me like using exceptions for handling these kinds of errors is in a way ignoring the problem, if you know that this piece of code could have an error, why not change it so that it cant have an error?
2. How to use exceptions?
Obviously i’m not understanding exceptions very well, but i do understand that its best practice(?), so how should exceptions be used?
Should a try/catch be wrapped around specific lines of code like this:
function doSomething(){
try{
if($var == "value"){
echo 'good';
}else{
throw new Exception();
}
}catch(Exception $e) {
echo 'bad';
}
try{
if($var2 == "value2"){
echo 'still good';
}else{
throw new Exception();
}
}catch(Exception $e) {
echo 'bad';
}
}
doSomething();
or should they be wrapped around the actual function to catch multiple exceptions like this:
function doSomething(){
if($var == "value"){
echo 'good';
}else{
throw new Exception();
}
if($var2 == "value2"){
echo 'still good';
}else{
throw new Exception();
}
}
try{
doSomething();
}catch(Exception $e) {
echo 'bad';
}
Can i wrap functions and classes in a try/catch, and if that function/class throws an exception catch it, or should each line that could throw an exception have the try/catch around it?
3. What counts as an exception?
If a user gets to a page they are not supposed to be on, for example a logged in user gets to the login page, i want to redirect that user to the home page, is that an exception?
Another example:
If a user submits a form and the form is corrupt in someway (not necessarily because of the code, maybe someone tried to hack the form, altered the form through the inspect element, etc.), i want to send the user back to the form, log the event, and show the user a general message, is this an exception?
4. Logging exceptions and showing users alerts
For some exceptions, like the form example above, i want to log the event and let the user know that something happened. For other exceptions i don’t.
I know there can be multiple exception classes inheriting from the main Exception() class, but is this best practice, or is having one general class for exception handling best?