phpexceptionerror-handlingtry-catch

When should you use PHP Exceptions?


I've seen lots of tutorials that demo simple try catches with, say, the act of opening a file. But I've never seen a big, "real" example. Can someone provide me with a few cases in which they have or would use exceptions? And is it really necessary to extend the exception class just to throw an exception? And finally, when throwing exceptions, does it cause the script to exit(); ? Or, does it log it and continue on with script execution?


Solution

  • We use exceptions extensively within our projects.

    One specific instance is for actions that require the user to be logged in or upon registration. We use Exceptions for flow control on error conditions. If the current user is not logged in we throw an exception. The exception handler then redirects them to the loggin page.

    Using our registration action as an example, we extend the Exception like this:

    class RegistrationFailed extends Exception {}
    

    Now in our catch statement within the registration code we can test for the RegistrationFailed exception and handle it accordingly. Otherwise, when the exception is not a RegistrationFailed, we allow it to bubble up because we are not interested in it.

    try {
        // do registration here
    }
    catch(RegistrationFailed $e) {
        // handle the failed registration
    }
    catch(SomeOtherException $e) {
        // handle other errors like this...
    }
    
    // All other errors will not be caught and will bubble up
    

    Another example is within our wrapper classes which developers must extended. We use Reflection to ensure the child classes have properly implemented their methods and provided the correct interface. If not we notify the developer of that class via Exceptions letting them know a specific interface or method must be provided by the child class.


    Edit: I can already hear the comments about "You shouldn't use error handling for flow control!" however, for the project discussed above, it was necessary.

    In the normal flow of the program a failed registration is expected due to the many validation rules that might fail, like a password that's too short.

    However, it's an ajax application, so it's possible that someone might try to access an ajax url manually, when they are not logged in. This is as exception and thus we handle it as such.