Heya, Frank.
The main advantage to using try/catch is that you can catch Exceptions *anywhere*.
For example (and using the doQuery() function above):
-
function runABadQuery()
-
{
-
doQuery( 'this is not valid SQL' );
-
}
-
-
ob_start();
-
-
try
-
{
-
echo 'You will never see this.';
-
-
runABadQuery();
-
-
echo 'You will never see this, either.';
-
}
-
catch( Exception $e )
-
{
-
// Alert admin
-
mail
-
(
-
'my@email.address',
-
'Exception thrown: ' . date('F j, Y g:i:s a'),
-
$e->getMessage()
-
);
-
-
// Clear the output buffer.
-
while( ob_end_clean() )
-
{
-
}
-
-
// Output an error message.
-
echo 'The server made a boo-boo. This should be your customized 500 error page. You could even use include() here if you wanted.';
-
-
// We're done here.
-
exit;
-
}
-
-
ob_end_flush();
-
Notice that even though the Exception gets thrown way down the stack in doQuery() [called by runABadQuery() called by main()], the Exception still gets caught.
In the code above, you can enclose the entirety of your code within a try/catch block, and if an Exception gets thrown *anywhere*, your code will stop, it will send an email with the text of the Exception to an administrator, and it will display a generic error page.
Note also that by using output buffering, you can prevent any output from reaching the browser until the script has successfully finished executing.