Try/Catch block in PHP not catching Exception

后端 未结 12 771
既然无缘
既然无缘 2020-12-04 13:45

I am trying to run this Example #1 from this page: http://php.net/manual/en/language.exceptions.php



        
相关标签:
12条回答
  • 2020-12-04 14:20

    I just had this exact problem where it seemed like I had even copied the name of the exception and yet it didn't catch it. It turned out it was my stupid mistake but I thought I should post my case here in case there is someone else in the same situation.

    I had my exception in my namespace called A and the script was in a namespace called B. The problem was that I had A\MyException which equals (in PHP) \B\A\MyException (because my script is in the namespace called B!). All I had to do to fix it was to add backslash (or whatever it's called) to the exception name so it would look like this: \A\MyException

    0 讨论(0)
  • 2020-12-04 14:22

    TLDR; make sure you have use Exception; on the top of both php files

    0 讨论(0)
  • 2020-12-04 14:26

    You can not use the typical try{} catch{} blocks in PHP as you could do in another language like C# (Csharp).

    If you do this:

    try{
        //division by zero
        $number = 5/0;
    }
    catch(Exception $ex){
        echo 'Got it!';
    }
    

    You will not see the 'Got it!' message never. Why? It's just because PHP always needs an Exception to be "Thrown". You need to set your own error handler and throw an Exception with it.

    See set_error_handler function: http://php.net/manual/es/function.set-error-handler.php

    0 讨论(0)
  • 2020-12-04 14:27

    Maybe try disabling certain 3rd party extensions you might have installed? http://bugs.php.net/bug.php?id=41744

    0 讨论(0)
  • 2020-12-04 14:29

    If you are using PHP 7, you may need Throwable instead of Exception

    0 讨论(0)
  • 2020-12-04 14:34

    \Exception doesn't work for me but I found a solution.

    I needed to replace try{}catch(Exception $e){} by try{}catch(Throwable $e){}.

    For more information : https://trowski.com/2015/06/24/throwable-exceptions-and-errors-in-php7/

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