PHP try-catch blocks: are they able to catch invalid arg types?

前端 未结 4 424
一整个雨季
一整个雨季 2020-11-30 12:37

Background: Suppose I have the following obviously-incorrect PHP:

    try{
        $vtest = \'\';
        print(array_pop($vtest));
    }cat         


        
相关标签:
4条回答
  • 2020-11-30 12:50

    The only way I can think of would be to do the following:

    try{
        $vtest = '';
        if(is_array($vtest)){
            print(array_pop($vtest));
        }
        else{
            throw new NotArrayException()
        }
    }catch(NotArrayException $exx){}
    

    Of course if you just want to do this silently you could just do the following since you don't need to catch any exception:

        $vtest = '';
        if(is_array($vtest)){
            print(array_pop($vtest));
        }
    
    0 讨论(0)
  • 2020-11-30 12:56

    A warning will always be produced by the code you provided but you can use set_error_handler to dictate how the warning is handled; i.e. you can cause it to throw an exception. Furthermore, you can use restore_error_handler to return to default error handling when your done.

    function errorHandler($errno, $errstr, $errfile, $errline) {
        throw new Exception($errstr, $errno);
    }
    set_error_handler('errorHandler');
    
    0 讨论(0)
  • 2020-11-30 12:58

    Warnings and notices are not technically exceptions in PHP. To catch an exception it has to be explicitly thrown, and many of the built-in libraries of functions do not throw exceptions (mostly because they were written before PHP supported exceptions).

    It would have been nice if somehow exceptions were built on top of the existing notice/warning/error framework but perhaps that is asking too much.

    0 讨论(0)
  • 2020-11-30 13:07

    You can catch such errors when you convert every error to an exception. I have set up a little error-handling environment. Just test it - it will work.

    0 讨论(0)
提交回复
热议问题