Question

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

Was it helpful?

Solution 2

<?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

OTHER TIPS

The reason at least for C++ is because checking for zero divisor and then throwing and handling an expetion can seriously affect performance on some systems. Thus division by zero is Undefined Behavior according to C++ standard.

5.6 Multiplicative operators

4 The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded;81 if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both a/b and a%b is undefined

Some implementations thru do throw exceptions. But relaying on that may lead to unexpected results if code compiled with different compiler. For example see SEH in msvc

5 Expressions

4 If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

Can't speak to PHP, but in C++ the code is compiled into native code with instructions for the CPU. It's not doing any high level processing so an exception getting generated doesn't make sense for such a primitive operation. Further, this type of validation would slow down math operations. The downside to exceptions is performance.

It's certainly possible the designers of PHP did not want to take the performance hit of checking for input errors on simple math operations as well.

In C/C++ on POSIX operating systems (for all practical purposes, everything but Windows), a signal SIGFPE gets sent to the the application whenever "an illegal arithmetic operation gets performed" (e.g. division by zero.) You'd use the signal system call to install a handler for this.

Signals are distinct from exceptions though, and you can't just start throwing exceptions from signal handlers -- signal handlers are executed in a different frame from the rest of the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top