Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use exception handling in php?

I've been programming PHP for a long time, but not so much PHP 5... I've known about exception handling in PHP 5 for some time, but never really looked into it. After a quick Google it seems fairly pointless to use exception handling - I can't see the advantages of using it over just using some if() {} statements, and perhaps my own error handling class or whatever.

There's got to be a bunch of good reasons for using it (I guess?!) otherwise it wouldn't have been put into the language (probably). Can anyone tell me of some good benefits it has over just using a bunch of if statements or a switch statement or something?

like image 860
John Hunt Avatar asked Jun 30 '11 05:06

John Hunt


People also ask

Why do we need exception handling?

Exception handling is useful for dealing with exceptions that cannot be handled locally. Instead of showing an error status in the program, the exception handler transfers control to where the error can be handled. A function can throw exceptions or can choose to handle exceptions.

Why are exceptions better than assertions?

Exceptions versus assertions It doesn't represent a condition that the program has to recover from at run time. An assert stops execution at the statement so that you can inspect the program state in the debugger. An exception continues execution from the first appropriate catch handler.


2 Answers

Exceptions allow you to distinguish between different types of errors, and is also great for routing. For example...

class Application
{
    public function run()
    {
        try {
            // Start her up!!
        } catch (Exception $e) {
            // If Ajax request, send back status and message
            if ($this->getRequest()->isAjax()) {
                return Application_Json::encode(array(
                    'status' => 'error',
                    'msg'    => $e->getMessage());
            }

            // ...otherwise, just throw error
            throw $e;
        }
    }
}

The thrown exception can then be handled by a custom error handler.

Since PHP is a loosely typed language, you might need to ensure that only strings are passed as arguments to a class method. For example...

class StringsOnly
{
    public function onlyPassStringToThisMethod($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentException('$string is definitely not a string');
        }

        // Cool string manipulation...

        return $this;
    }
}

...or if you need to handle different types of exceptions in different ways.

class DifferentExceptionsForDifferentFolks
{
    public function catchMeIfYouCan()
    {
        try {
            $this->flyForFree();
        } catch (CantFlyForFreeException $e) {
            $this->alertAuthorities();
            return 'Sorry, you can\'t fly for free dude. It just don\'t work that way!';
        } catch (DbException $e) {
            // Get DB debug info
            $this->logDbDebugInfo();
            return 'Could not access database. What did you mess up this time?';
        } catch (Exception $e) {
            $this->logMiscException($e);
            return 'I catch all exceptions for which you did not account!';
        }
    }
}

If using transactions in something like Zend Framework:

class CreditCardController extends Zend_Controller_Action
{
    public function buyforgirlfriendAction()
    {
        try {
            $this->getDb()->beginTransaction();

            $this->insertGift($giftName, $giftPrice, $giftWowFactor);

            $this->getDb()->commit();
        } catch (Exception $e) {
            // Error encountered, rollback changes
            $this->getDb()->rollBack();

            // Re-throw exception, allow ErrorController forward
            throw $e;
        }
    }
}
like image 182
webjawns.com Avatar answered Oct 02 '22 07:10

webjawns.com


Exception handling: If condition versus Exception isn't specific to PHP, but gives a good perspective. Personally, Exception(s) & try/catch are implemented in languages to enforce good behaviour amongst developers that normally wouldn't be as attentive to error checking / handling.

If you are confident that your if/else if/else is catching all scenarios, than cool.

Here is an overview of the Advantages of Exceptions - Java -- At one point, there is a snippet of code that has many if/else statements and the following excerpt:

There's so much error detection, reporting, and returning here that the original seven lines of code are lost in the clutter. Worse yet, the logical flow of the code has also been lost, thus making it difficult to tell whether the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing when you modify the method three months after writing it. Many programmers solve this problem by simply ignoring it — errors are reported when their programs crash.

So really, it comes down to personal preference in the end. If you want code that is readable and can be consumed by other people, it's generally a better approach and enforces best-behaviour

like image 31
sdolgy Avatar answered Oct 02 '22 06:10

sdolgy