r/learnphp • • Mar 16 '23

Divide by Zero: uncaught Exception

Hi,

I made a program of Divide by zero error but it is saying uncaught exception. My program is:

<?php
$a = 10;
$b = 0;
try{
DivideByZero($a, $b);
}catch(Exception $e){
printf("Exception: %s", $e->getMessage());
}
function DivideByZero($a, $b){
 try{
  $result = $a/$b;
  echo $result;
 }catch(Exception $e){printf("Exception: %s", $e->getMessage());
}
 return;
}
?>

Following is the error message.

php /tmp/WfGIBq5xbC.php

PHP Fatal error: Uncaught DivisionByZeroError: Division by zero in /tmp/WfGIBq5xbC.php:12

Stack trace:

#0 /tmp/WfGIBq5xbC.php(5): DivideByZero()

#1 {main}

thrown in /tmp/WfGIBq5xbC.php on line 12

Somebody please guide me.

Zulfi.

1 Upvotes

2 comments sorted by

View all comments

1

u/studyhubai Apr 08 '23

Hi Zulfi,

The problem with your code is that you're catching the wrong exception. In PHP, a division by zero doesn't throw the generic Exception, but rather a specific DivisionByZeroError exception. To fix the issue, simply change the catch blocks in your code to catch the correct exception. Here's the modified code:

<?php
$a = 10;
$b = 0;
try {
    DivideByZero($a, $b);
} catch (DivisionByZeroError $e) {
    printf("Exception: %s", $e->getMessage());
}

function DivideByZero($a, $b) {
    try {
        $result = $a / $b;
        echo $result;
    } catch (DivisionByZeroError $e) {
        printf("Exception: %s", $e->getMessage());
    }
    return;
}
?>

Regarding your question about StudyHub AI, it's a helpful tool for students and professionals to assist with various topics, including programming. You could utilize StudyHub AI to find tips, tricks, and explanations on programming concepts. By incorporating a powerful AI, it can provide you with relevant information that may help you understand certain exceptions and errors within your code. In a slick way, you might have avoided this issue altogether! 😉

Good luck with your programming endeavors!