My try-catch doesn' t "catch". What's wrong?

My try-catch doesn' t "catch". What's wrong?

Post by lwood » Tue, 09 Aug 2005 06:05:07


Why isn't my "catch" catching?

TIA,

Larry Woods

This script get's this output::

Warning: Division by zero in C:\Inetpub\wwwroot\PHP\tests.php on line 4
This will never be printed

Script: ( 5.0.4; XP Pro; IIS )

<?php
try
{
print 2 / 0; // simple error - division by zero
print "This will never be printed";
}
catch (Exception $e)
{
print "Exception caught:<br>";
print "Code: ".$e->getCode()."<br>";
print "Message: ".$e->getMessage()."<br>";
print "Error thrown on Line: ".$e->getLine()."<br>";
print "Trace: <br>".$e->getTraceAsString."<br>";
}
?>
 
 
 

My try-catch doesn' t "catch". What's wrong?

Post by Janwillem » Tue, 09 Aug 2005 06:18:10


With try-catch only exceptions which are actually thrown will be handled,
not warnings:

class Math {
function divide($a, $b) {
if ($b == 0) {
throw new Exception('division by zero');
} else {
return $a / $b;
}
}
}

try {
$math = new Math;
print $math->divide(2, 0);
}catch (Exception $e) {
print "Exception caught:<br>";
print "Code: ".$e->getCode()."<br>";
print "Message: ".$e->getMessage()."<br>";
print "Error thrown on Line: ".$e->getLine()."<br>";
}


JW

 
 
 

My try-catch doesn' t "catch". What's wrong?

Post by lwood » Tue, 09 Aug 2005 06:38:34

Thanks....

Larry
 
 
 

My try-catch doesn' t "catch". What's wrong?

Post by Wayn » Wed, 10 Aug 2005 02:00:43


...But you can throw exceptions from the error handler (see
set_error_handler()) and this will work correctly. So you could throw
a generic exception from the error handler which would get called on
divide by zero and then be caught by your exception handler.