Using Try-Catch blocks in PHP

Try-Catch blocks are a great structure to use on your PHP applications and some times, it will be the only way to figure out a given error.

Consider a Order class that, inside the save method, activate the save method of the OrderItem class. If you don’t have a try catch block you might never see what went wrong on the OrderItem class in the case of a query fail.

This was precisly my scenario this morning. Everything was saving correctly besides the OrderItem. I have tryed the common debug method (echo each line) and couldn’t see the error, so I have used the try-catch block (which, strangely enough, wasn’t there by default).

After placed the block, executed, there it was – a freaking misspelling that made a whole application go wrong.

Spelling fixed and now everything is working, but imagine if in PHP we din’t have try-catch blocks, would you be able to find the error on the following code?

$item_data = array(
‘longDescription’ => $this->LongDescription,
‘skuNumber’ => $this->SKUNumber,
‘weihgt’ => $this->Weight,
‘height’ => $this->Height,
‘width’ => $this->Width,
‘priceJobber’ => $this->Jobber,
‘priceCost’ => $this->Cost,
‘deleted’ => $this->deleted,
‘partID’ => $this->PartID,
‘img’ => $this->imgPath
);
$GLOBALS[‘db’]->insert(DB_PREFIX.’order_item’,$item_data);
$itemid = $GLOBALS[‘db’]->lastInsertId();
if(is_numeric($itemid) && $itemid > 0){
$this->orderItemID = $itemid;
}
return true;

Anyway, if you will be working with data modification on database you should use the try-catch block and if it is well used you will have a more secure, reliable and error handled application.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

One response to “Using Try-Catch blocks in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: