Monday, 25 April 2016

php - Exceptions are not recognised as a class and are not caught

I'm fairly new to PHP programming and I'm trying to implement some really basic exception handling in my code. However, it seems like "Exception" is not recognised as a class at all and thus no exceptions are caught.



Here is a basic code example, which doesn't work for me:



try
{
$x = 0;

$y = 1;

$z = $y / $x;
}
catch (Exception $e)
{
echo "Hello World!";
}
?>



When I run this code, I get the following message instead of the expected "Hello World!":




Warning: Division by zero in C:\myFolder\testCase.php on line 7




What I tried so far:





  • use "\Exception" instead of "Exception" to get into the general namespace and maybe find the class there


  • make the namespace known by writing use Exception or similar expressions at the beginning of the code


  • used various other class names instead of "Exception" (e.g. ErrorException, Error, Throwable, DivisionByZeroError ... don't remember all I tried)




If I use the "throw" keyword, it will jump to the catch block just fine. But it should catch Exceptions like Division By Zero automatically, without me having to throw one, right? At least that's what I gathered from searching the web (and this is also the case for other programming languages).



I also thought about using set_exception_handler, but I don't know how I would get specific Exception information that way since I can't use Exception->getMessage(). The only way would be - again - to throw every single exception manually.



What do I have to do in order to make the catch block catch all thrown Exceptions?




If it matters: I'm using PHP Version 7.3.0.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...