1

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.

user31782
  • 7,087
  • 14
  • 68
  • 143
  • First, it partly depends on the type of exception you are talking about. “Go to store. Buy milk. Drink milk.” If the middle step throws an exception, you will be arrested. Similarly, if a database connection fails, future reads and writes will probably fail, or at least leave you in an inconsistent state. Exceptions are generally classified as recoverable or non-recoverable, and good code will tell you what exceptions might be thrown. If a function throws a Divide By Zero exception, what does that mean to your future code? – Chris Haas Oct 15 '21 at 12:12
  • I personally almost never use try/catch, and instead rely on making sure my data is in an expected pattern, for instance, so a divide by zero can never happen, or that an expected array key does exist, which is called defensive programming. If the infrastructure fails, however, I’ve got bigger problems. When I do use a try, it is around as little code as possible, just one function or block, and it is because I know I can recover. If someone uploads an image, and the processor can’t handle it, I can tell the user that the image isn’t supported, for instance. – Chris Haas Oct 15 '21 at 12:17
  • The possability of calling a function that does not exist should IMHO be zero, as you are writing the code. And if somehow there is a chance the function doesn't exist, test beforehand with [`function_exists()`](https://www.php.net/manual/en/function.function-exists.php) – Michel Oct 15 '21 at 13:10

0 Answers0