0

I am simply trying to put a arithmetic expression around try-catch block.

Here's what I tried:

 try { $result = 4/0; } catch (Exception $e) { d($e->getMessage()); } 

But instead of printing $e->getMessage(), it is displaying Internal Server Error Division By Zero which is similar if I don't use any try-catch.

What am I doing wrong?

0

2 Answers 2

1

You can't catch DivisionByZeroError on normal arithmetic because PHP considers it a warning, not an error. Instead you need to set an error handler to look for it e.g.

function handler($errno, $error) { if ($error == "Division by zero") { echo "Error $errno! $error\n"; return; } // hand processing back to the standard handler return false; } set_error_handler('handler'); $result = 4/0; 

Output:

Error 2! Division by zero 

Note that the error handler should return control to the standard handler (by returning false) if this is not the error you were looking for.

Sign up to request clarification or add additional context in comments.

Comments

1

You got to use this:

try { $result = intdiv(4, 0); } catch(DivisionByZeroError $e) { d($e->getMessage()); } 

PHP manual : http://php.net/manual/en/class.divisionbyzeroerror.php (Works with PHP 7 onwards)

Update: Using intdiv() - Integer division (Works with PHP 7 onwards)

7 Comments

Amit Merchant, nope still the same.
I've updated my code. Please try now. Basically I've used intdiv() function to perform the division operation which perfectly captures the exception.
it is still giving me the same Internal Server Error despite of all the updates. is it working on yours as expected?
still getting the Server Error instead of exception message. was it supposed to be so?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.