Consider the following javascript code debugging example:
try {
existentFunction1();
nonExistentFunction();
existentFunction1();
existentFunction1();
} catch (error) {
console.error(error); // expected output: ReferenceError: nonExistentFunction is not defined
}
The whole point of using try...catch
is I don't pre-know which function inside try
will throw error on runtime, that is when a user is interacting with the website in a way that executes the code inside the try
statement, I don't want the code to halt if one of the functions doesn't work as expected.
Now If I wanna do the same in php I need to put a throw
statement (at least in php < 8, this post suggest we don't need throw).
Php code:
try {
function1();
function2();
// where to put throw? Before or after function3()?
function3();
function4();
}
catch(Exception $e) {
echo "Redirect the user to 404 page";
}
One way out of this, I think is to use try...catch
for every suspected function, which defeats the purpose of using try catch
, just use a switch
or if-else
for all functions. Or, if I already know which function could generate error, I don't need try-catch at all.
What am I missing in php exceptions? ...Coming from a javscript programming background.