Search code examples
phpc++exceptiondivide-by-zero

Why exceptions have to be thrown manually?


I have tried this in PHP and C++ so my question is specifically about them only. Why do we have to throw exceptions ourself and they are not thrown automatically when an exception issue occurs.

PHP Code First

<?php 
try{ 
$a=1;
$b=0;
echo $a/$b;
} catch (Exception $e) { 
    echo "Error : ".$e->getMessage();
} 
?> 

Why does this code not throw a Divide by zero exception?. It can be done by following

<?php 
  try{ 
    $a=1;
    $b=0;
    if($b==0)
    {
          throw new Exception("What's the point in an exception if its not automatic and i have to throw it myself");
    }
    echo $a/$b;
    } catch (Exception $e) { 
        echo "Error : ".$e->getMessage();
    } 
?> 

But what's the point in exception handling then if I have to code for possible exceptions myself, then why not use any simple error reporting pattern?

Same stands true for the following

C++ CODE

int main()
{
try{ 
    int a=1;
    int b=0;
    cout<<(a/b);
  }
   catch (string e)
     {
         cout << e << endl;
     }
}

This does not generate an exception, generates runtime error and crashes the app as would be expected if exception handling was not in place. Following works

int main()
{
try{ 
    int a=1;
    int b=0;
    if(b==0)
    {
     throw string("What's the point in an exception if its not automatic and i have to throw it myself");
    }
    cout<<(a/b);
  }
  catch (string e)
  {
     cout << e << endl;
  }
}

Question

Why did I have to check for those variables manually in order to catch the error? Is an exception really an exception when I already tell the code that this will happen? Then why is it preferred above basic if conditions


Solution

  • <?php
    
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
    set_error_handler("exception_error_handler");
    
    try{
        $a=1;
        $b=0;
        echo $a/$b;
    } catch (Exception $e) {
        echo "Error : ".$e->getMessage();
    }
    

    output:

    Error : Division by zero