Try/Catch block in PHP cannot catch exception situations
P粉226413256
2023-08-22 15:19:37
<p>I'm trying to run this example #1, from this page: http://php.net/manual/en/language.exceptions.php</p>
<pre class="brush:php;toolbar:false;"><?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "n";
echo inverse(0) . "n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n";
}
// Continue execution
echo "Hello Worldn";
?></pre>
<p>However, the output I get is not expected: </p>
<pre class="brush:php;toolbar:false;">0.2
Fatal error: Uncaught exception 'Exception' with message 'Division by zero.'
inxxx:
7 Stack trace: #0 xxx(14): inverse(0) #1 {main} thrown in xxx on line 7</pre>
<p>The development environments I use are <code>UniServer 3.5</code> and <code>PHP 5.2.3</code></p>
I just ran into this exact problem, it feels like I've even copied the name of the exception and it's not catching it. Turns out to be a stupid mistake on my part, but I thought I'd post my situation here in case anyone else is in the same situation.
My exception is called A in my namespace and the script is called B in one namespace. The problem is that I have a A\MyException which is equal (in PHP) to \B\A\MyException (because my script is called B# in the namespace ##!). All I had to do was add a backslash (or whatever it was called) before the exception name to fix it so it looked like this: \A\MyException