简体   繁体   中英

Why can't I catch a TypeError with set_error_handler()?

Here is code:

<?php
function hola(int $hola)
{
    return $hola;
}
function handler($errno, $errstr, $errfile, $errline)
{
    echo 'handler';
}
set_error_handler("handler");
hola('hola');

Here is Error:

Fatal error: Uncaught TypeError: hola(): Argument #1 ($hola) must be of type int, string given, called in C:\laragon\www\estudiophp\script.php on line 12 and defined in C:\laragon\www\estudiophp\script.php:2 Stack trace: #0 C:\laragon\www\estudiophp\script.php(12): hola('hola') #1 {main} thrown in C:\laragon\www\estudiophp\script.php on line 2

The Fatal error: Uncaught TypeError: is an exception, not an error. To capture exceptions you need to register a exception handler . Using your handler function as an example, here is what an exception handler would look like.

function exception_handler($exception)
{
    echo 'Exception Handler';
}
set_exception_handler("exception_handler");

You are able to use both the set_error_handler and set_exception_handler functions together to capture both errors and exceptions separately.

function exception_handler($exception)
{
    echo 'Exception Handler';
}
function handler($errno, $errstr, $errfile, $errline)
{
    echo 'Handler';
}
set_exception_handler("exception_handler");
set_error_handler("handler");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM