Forum Moderators: coopster

Message Too Old, No Replies

Importance of Exceptions

         

Mister_L

10:25 pm on May 17, 2011 (gmt 0)

10+ Year Member



Hi,

This example is taken from the php manual:


function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}

try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}



The thing that I don't get is, why throwing an exception is any better than simply echoing 'Division by zero' inside inverse function? Can you show me a concrete example where throwing an exception has advantage over if?

Thanks.

rocknbil

5:05 pm on May 18, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I agree, the difference is a little esoteric, but basically, exceptions allow you to manage error conditions externally without internal echoes. This article [download.oracle.com] does a very good job of explaining the difference. I'm guilty of error trap clogging myself. :-P

In PHP it's not as big of a difference as when you're programming in machine code languages that can crash systems, but if you get into large programs with lots of classes it becomes important.