Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are exceptions in php really that useful?

3 days ago I started rewriting one of my scripts in OOP using classes as a practice after reading a lot about the advantages of using OOP.

Now I'm confused weather I should use exceptions or not. They seem to make my work harder and longer.

My application check if the data was sent through an Ajax request or not then uses that info through the script.

Check this example :

 /*
 * The older way
 */

if($ajaxEnabled) {
    $error = errorWrap('Ajax error');
} else {
    $error = errorWithBackLinkWrap('NoAjax error');
}

function doSomething() {
    if(empty($POST['name'])) {
            die($error);
    }
}

/* 
 * OOP way
 */

class someClass {
    private $_ajaxEnabled;

    public function doSomething() {
        try {
            if(!$this->_isDateValid()) {
                if($this->$_ajaxEnabled) {
                    throw new ajaxException('Ajax error');
                } else {
                    throw new noAjaxException('NOAjaxError');
                }
            }
        } catch(ajaxException $e) {
            echo $e->getErrorMessage();
        } catch(noAjaxException $e) {
            echo $e->getErrorMessage();
        }
    }
}

This code is only for demonstrating the problem, so I know there are some undefined functions in it :).

So before going oop, error handling was easier for me because I only had to echo the appropriate error.

Now using exceptions, in every function I have to check the type of connection first then write 2 catch functions for each thrown exception, which lead to a much larger code.

I'm really new to OOP in php so maybe there is a cleaner and a better way to do this, is there ?

like image 327
Maher4Ever Avatar asked Aug 23 '10 15:08

Maher4Ever


People also ask

Should we always use exceptions?

Use exceptions when the code that handles the error is separated from the code that detects the error by one or more intervening function calls. Consider whether to use error codes instead in performance-critical loops, when code that handles the error is tightly coupled to the code that detects it.

When should exceptions not be used?

Don't use exceptions to signal something completely normal. Don't use exceptions to control your normal application flow. Use return values or state fields for flow control instead.

Why we are using exception handling in PHP?

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved.

Why is exception handling a good idea what is it good for?

The save method handles exceptions without propagating them, simply returning false , while save! raises an exception when it fails. This gives developers the option of handling specific error cases differently, or simply handling any failure in a general way.


1 Answers

Your question is not uncommon, whether/when to use exception is sometimes a philosophical decision and many experienced developers can't wrap their heads around it.

That being said, I've found that listing out the distinct properties of each way of handling error makes it easy to choose your preferred way:

Return code

  • The caller can ignore it or forget to check it
  • The caller usually needs more documentation reading before he can use it (does 0 mean success or failure?)
  • Object destruction is not guaranteed -- it all depends on the caller to clean up properly

When to use: It's pretty obvious. Use return codes when you trust the caller (internal code or trivial errors which can be safely ignored).

Exceptions

  • The caller cannot ignore it
  • The caller can still suppress it if he wants (with an empty try/catch)
  • Object destruction takes places properly -- most of the time

When to use: When you don't trust your caller as much (third party) or you really need to make sure your error code doesn't go ignored.

Die

  • Cannot be ignored and cannot be suppressed

When to use: It's usually obvious enough. You need everything to stop immediately.

(In a PHP context, I don't think it makes much difference. The above suggestions should still apply.)


(Aside)

Usually it's tempting to just write out an error message when something bad happens (especially when the first programming language you learned is PHP :P). But if you really want to grok OOP, it's not a proper way to handle errors.

Every object or every function should ideally only perform one function. If one function writes error to the screen and does its own thing, it's difficult to later switch to a DatabaseErrorLogger or TextFileErrorLogger or etc. One approach would be to supply a logger to use (this is called Dependency Injection). Another way to do it is to use exception -- this way, the caller gets to choose which ErrorLogger to use.

like image 139
kizzx2 Avatar answered Sep 21 '22 15:09

kizzx2