This is the final post in my series about PHP exceptions and looks at how when an exception occurs, script execution may continue depending on how the exception is handled.
Examples
I've been using PHP's PDO library recently instead of the more traditional approach of using the database specific functions such as the mysql_* functions. PDO is an object oriented approach and uses the exception model to throw errors. It is a useful example to show how execution will continue even if an exception is thrown when attempting to connect to the database.
The two examples below attempt to establish a connection to a MySQL database using a database, login name and password that do not exist, defined as follows:
The first example doesn't bother attempting to catch the exception and execution will halt before getting to the line 'echo "code continues here\n";':
This will output the following:
Because the exception is not handled, the error message will be displayed and execution will halt. Ideally we do not want to display error messages such as the above.
On the other hand, if we handle the exception without ending the script using exit or die:
then this is what will be echoed:
In the event of an exception occurring that means the script cannot continue to run, such as not being able to connect to the database, execution should halt (after doing whatever logging or emailed notifications etc is required).
This is often as simple as using exit to end the script's execution like so:
The PHP Exception Series
This concludes my series on PHP exceptions. See the related posts below for earlier posts in the series.
0 comments:
Post a Comment