The missing art of exception handling

First I would like to start by a quote I’ve learnt from Dr.yasser farouk (one of the doctor I’m proud to learned from) ‘as a developer it’s a shame to let the OS throw your code out of CPU because of division by zero or array out of bounds’

He was right about that and it’s also a good behavior and makes It easy for the developer to eliminate bugs. For example: you’re trying to persist a user object in database which has no ’email’ property set(which is required by your class responsible for db operations). This will throw an exception says that ’email’ property should not be null and then you should have an if statement to check if the required properties are not nulls (which is a really big hassle for an object with 20 property for example).

For me as a web developer (who writes in php) exception handling saves me a lot of time spent of dangling if else to check every single case. Using exception handling makes it easy as putting the code which I suspect in a try block such as follows:

try {
    $fbdata = $facebook->get($fbToken, $fbId);<br />
} catch (\FacebookApiException $e) {<br />
    throw new Exception\AuthenticationFailedException('User exists but Facebook token invalid');<br />
}

As an architect you should start designing classes to serve your custom exceptions.

As a Symfony2 lover I’ll show you an example how to do it in Symfony by extending the existing exception classes:

<?php
namespace Smartizer\EventxBundle\Service\Exception;</p>
class AuthenticationFailedException extends LogicException
{
}

as you may notice it’s pretty easy to get started and saves you alot of time spend on checking and dangling if else.

hope you’ve liked my post and start defining your custom exceptions.