Why try catch does not catch error level notice? namely, it does not catch the existence of an array index.
- stackoverflow.com/questions/3261051/… - L. Vadim
- @ L.Vadim link to English WITH, so it’s better to translate the answer than hinting at a double. - Naumov
- try to translate if it helps - L. Vadim
- one@ShuhratjonJumaev he does not catch because in php, try ... catch handles exceptions, and notice is an error. - Naumov
- oneSet set_exception_handler and in the callback of the function throw exceptions with the text of the error line number, etc. callback example you can see here php.net/manual/en/language.exceptions.php - Naumov
2 answers
Because try works with exceptions . A notice is an error message.
In order for PHP to handle errors as exceptions, you need to set up a custom error handler so that it starts throwing out exceptions on errors. The easiest will look like this:
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line) { throw new ErrorException ($err_msg, 0, $err_severity, $err_file, $err_line); }); If you add this code at the beginning of the PHP file, then all errors will raise exceptions.
You can also extend this code by making it so that an exception of a particular type is thrown for each type of error.
This is solved simply by adding in your code (conditional example)
if(!array_key_exists($x[5])) throw new Exception('Не найден ключ '.5.' в массиве $x'); and already in the executable code you can catch this error
In order to be correctly understood, I enclose an article where the error trapping method written by a programmer in the financial sphere is described in detail. Habrahabr
- By the way, notice is not a mistake at all :) This is a warning - Mcile
- I recommend putting the above code in a function or in a class, and catching it when calling a function or class - Mcile