Using PHP with Java - An Exceptionally Clever Cow
(Page 6 of 7 )
Next, let's look at exception handling. If you go back to the example on the previous page, you'll see that the Java class includes a couple of exception handlers, one for IOExceptions and one for everything else. Let's now modify the PHP script so that it includes some basic exception handling.
<?php
// create an instance of the ReverseString object
$obj = new Java("ReverseString");
// create an instance of the StringWriter object
$writer = new Java("java.io.StringWriter");
$obj->setWriter($writer);
$obj->reverse("The cow jumped over the moon");
// get the last exception
$e = java_last_exception_get();
if ($e)
{
// print error
echo $e->toString();
}
else
{
echo $writer->toString();
$writer->flush();
$writer->close();
}
// clear the exception
java_last_exception_clear();
?>
This version of the script uses two built-in PHP functions to
check whether or not any exceptions were raised during the execution of the class methods. If any exceptions were raised, they would be stored in the $e PHP variable, and printed via a call to the toString() method.
If you'd like to see how an exception is handled, modify the PHP script above to look like this:
<?php
// create an instance of the ReverseString object
$obj = new Java("ReverseString");
// create an instance of the StringWriter object
$writer = new Java("java.io.StringWriter");
// deliberately introduce an error by commenting out the next line //
$obj->setWriter($writer);
// suppress errors here
@$obj->reverse("The cow jumped over the moon");
// get the last exception
$e = java_last_exception_get();
if ($e)
{
// print error
echo $e->toString();
}
else
{
echo $writer->toString();
$writer->flush();
$writer->close();
}
// clear the exception
java_last_exception_clear();
?>
Here's what the output looks like:
java.lang.Exception: Something really bad happened
Of course, this simple and graceful error message gets a
little more unfriendly if you remove the @ error-suppression operator.
Warning: java.lang.Exception: Something really bad happened in
/usr/local/apache/htdocs/java/exception.php on line 10
java.lang.Exception: Something really bad happened
Next: Beanie Baby >>
More PHP Articles
More By Harish Kamath, (c) Melonfire