What is an Exception?

Exceptions occur when an unexpected event happens in your code. There are two ways in which an exception can be created in our code example; an empty form could be submitted (all text fields left empty), or the program could fail to make the necessary connection to the server to open the text file for reading or writing. Exception handling means catching these instances and presenting an error message to the user about what has happened.

 

Validating the Form Fields

When we process the order we add the number of items and store it in a variable called $total_qty using the following lines of code;

 

$total_qty = 0;
$total_qty = $hd_qty + $mon_qty + $pr_qty;

 

We now add a conditional statement to check that $total_qty has a value in it;

 

if( $total_qty == 0 )
{
echo '<p><strong>You did not order anything</strong> <br />';
echo 'you must fill in at least one category <br />';
echo 'Please try again<br /></p></body></html>';
exit;
}

 

The exit statement stops any further processing of the code, so the error message is the only thing that will be displayed on the page. Notice that we put </body> and </html> tags in our echo statement, as the page ends as soon as the exit statement is executed.

You can also do the same thing using the function empty();

 

if ( empty ( $total_qty))
{
echo '<strong>You did not order anything</strong> <br />';
echo 'you must fill in at least one category <br />';
echo 'Please try again<br />';
exit;
}

Testing the Text File

When we read or write data, we need to first open the file using the following command.

 

$orderform = fopen("$DOCUMENT_ROOT/orders.txt", 'ab');

 

If for any reason the file cannot be opened, the variable $orderform will return ‘false', and an error message will display on the screen. The automatically generated error messages are a bit cryptic, so we are going to provide our own message instead.

 

@ $orderform = fopen("$DOCUMENT_ROOT/orders.txt", 'w');
flock($orderform, LOCK_EX);
if (!$orderform)
{
echo '<p><strong> Your order could not be processed at this time. '
.'Please try again later.</strong></p></body></html>';
exit;
}


fwrite($orderform, $order, strlen($order));
flock($orderform, LOCK_UN);
fclose($orderform);

 

Two things to notice, first the '@' character in front of the first line; this is an error suppression character which turns off the built in error messages. Second the '!' character in the if statement; this character essentially means 'not', and so the if statement reads 'if not $orderform' and will proceed if there is a value of 'false' stored in $orderform

Notice how we get a lock on the file before we check for errors. We don't want to have someone else lock on to the file while we are checking. We have now provided messages to the user if or any reason they cannot place their order.