-3

if i have the code below:

try {

   //call function a
   $object->function_a();

   //call function b
   $object->function_b();

   //call function c
   $object->function_c();

}
catch(Exception $e) {
   
     $error->track_error();
    
}

how can i catch syntax errors, like someone is changing the function_b() name to function_d() which doesn't exists.

it seems that try and catch doesn't catch syntax errors, it doesn't work without an if statement to check if something is wrong.

but if i can expect an error with an if statement, why do i need try and catch, i can just write something like this:

if(//something is false) {

  $error->track_error();
 
}

what i'm looking is something that will create an exception and jump to a catch block on the whole try scope, when any php error (including syntax) is happening, catch it and then get the details with error_get_last() or similar function for error logging inside the db.

is this possible?

  • 1
    Calling an undefined function is not a syntax error. Real syntax errors (the ones making the code impossible to interpret) cannot be caught by a try-catch block because a syntax error is thrown before the code is even executed. The question is, what do you mean by syntax error? The real ones or did you accidentally use the expression "syntax error" when you meant some other type of error? – El_Vanja Jan 15 '21 at 12:58
  • so how do you catch syntax errors, like ';' that doesn't exists, or fatal errors , like function that doesn't exists, or any unexpected errors that you can't predict with if-else condition? – Erik burton Jan 15 '21 at 13:05
  • You can't catch a syntax error (like a missing semicolon). In order to catch it, the code would have to run. But it can't run, because it has a syntax error and cannot be interpreted. For the other types, see [how to catch a fatal error](https://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-e-error-error). – El_Vanja Jan 15 '21 at 13:08
  • Expecting to be able to catch syntax errors within the same file as the error is in, is about the same, as to expect a drowning person to be able to just pull themselves out of the water by their own hair … no, _of course_ that won’t work. You need the script to _execute_ to be able to catch anything, but it _won’t_ execute, _because_ it contains syntax errors. How can one not realize what a catch-22 that is? – misorude Jan 15 '21 at 13:32

1 Answers1

0

You can use set_error_handler() to throw a custom Exception :

set_error_handler(function(int $errno, string $errstr, string $errfile = '', int $errline = 0) {
    throw new Exception("$errstr ($errfile, line $errline)");
});
Syscall
  • 19,327
  • 10
  • 37
  • 52