I created my own exception handler and set it using set_exception_handler().

Is there any reason I would need to use try/catch blocks anymore? I am trying to throw my own exceptions where necessary myself.

Any additional insight would be helpful. I am doing the same with errors as well.

    sosothirsty;10995804 wrote:

    Is there any reason I would need to use try/catch blocks anymore?

    Well yeah, usually you'd want to try to catch certain exceptions and handle them gracefully. A global exception handler can't really know how to do that in every possible situation it might get used.

    To me, the default exception handler is still a last resort even if I've replaced PHP's with my own; if I'm seeing it, it probably means I didn't write my code very well to handle error conditions.

      If you're throwing errors, then presumably you're wanting to catch them as well so that you can recover as soon as appropriate.

        bradgrafelman;10995807 wrote:

        Well yeah, usually you'd want to try to catch certain exceptions and handle them gracefully. A global exception handler can't really know how to do that in every possible situation it might get used.

        To me, the default exception handler is still a last resort even if I've replaced PHP's with my own; if I'm seeing it, it probably means I didn't write my code very well to handle error conditions.

        Can you go into it more with how to handle them more gracefully? All I was concerned about was making sure scripts halt when needed and appropriate error msgs be emailed to me when exceptions are thrown.

        I'll throw out a simple example of checking if my parameter is not empty.

        if(empty($var){
        throw new Exception('Parameter unexpectedly empty....."); 
        }

        What do you mean write my code better to handle error conditions? Maybe a more complex example would better illustrate this need. 😕

          Here's an article on exception handling in PHP, which I copied straight from the Wikipedia article on exception handling.

          For a more complex example, this one is from the Zend Framework.

          
              try {
                  $this->_jumpToTable('OS/2');
              } catch (Zend_Pdf_Exception $e) {
                  /* This table is not always present. If missing, use default values.
                   */
                  if ($e->getCode() == Zend_Pdf_Exception::REQUIRED_TABLE_NOT_FOUND) {
                      $this->_debugLog('No OS/2 table found. Using default values');
                      $this->fontWeight = Zend_Pdf_Font::WEIGHT_NORMAL;
                      $this->fontWidth = Zend_Pdf_Font::WIDTH_NORMAL;
                      $this->isEmbeddable = true;
                      return;
                  } else {
                      /* Something else went wrong. Throw this exception higher up the chain.
                       */
                      throw $e;
                  }
              }
          

            First off, you should throw more appropriate exceptions. For your example I would have thrown InvalidArgumentException but then I always try to throw specific exceptions so that when handling them I can handle DB related exceptions differently than argumentexception etc.

            Secondly, by writing better code I believe they mean using try/catch blocks to properly handle exceptions where they should be handled, as opposed to being sent all the way to the top of the stack trace to your default handler.

              sosothirsty;10995836 wrote:

              All I was concerned about was making sure scripts halt when needed and appropriate error msgs be emailed to me when exceptions are thrown.

              And therein lies the problem, if you ask me.

              In other words, you aren't concerned with auxiliary issues when such an error occurs. For example, depending upon the application, you might need to:

              1. Finish rendering the page and include an error message, or perhaps simply redirect the user (somehow - header() won't work if you've already started to output data) to an error page.

                After all, I'm assuming you aren't creating these web applications just for yourself but for the benefit of the people who use/view your website. Why, then, aren't you concerned about them?

              2. Clean up resources created/modified/etc. before the error occurred. For example, if you're handling a file upload that you just moved into its appropriate location, an error occurring in the SQL query to store that file's details in your DB would mean that you're now in an inconsistent state - you've got a file that looks as if it's been processed, yet it's nowhere to be found in the DB. A try/catch block would allow you to remove that file or otherwise flag it as "not really processed" due to the error.

              I'm sure others can think of many more, but the point is that sometimes there is more to do when handling an error other than e-mailing the error to yourself and just hoping everything else (including the clueless end user) can just deal with it.

                Ok, I did some reading and thinking on this. I realize now that I didn't fully understand the difference between errors and exceptions and didn't know enough about error handling as a whole. I went through a few books but most of them only explain the basic try/catch structure and custom handlers. I'm sort of stuck on how I want to handle my errors going forward. I'd like to quote this article.

                There are a number of views regarding when and how exceptions should be used. Some programmers feel that exceptions should represent fatal or should-be-potentially-fatal errors only. Other programmers use exceptions as basic components of logical flow control. The Python programming language is a good representative of this latter style: In Python exceptions are commonly used for basic flow control.

                This is largely a matter of style, and I am inherently distrustful of any language that tries to mandate a specific style.

                This is where I'm at currently. I'd like to list these points up more as a question of whether if I am heading in the right direction or not. Thanks again for all your responses, it has been helpful.

                1. I will continue to use my custom error handler and direct errors depending on the error level. I'm not sure what route to take on this whether it be logging to file, to db or using email.

                2. Would it be bad styling and practice to continue to use a custom expection handler for the bulk of my exceptions that do not require additional "handling"? My thoughts are if I'm doing something such as handling file uploads, I can use a try/catch block to control the errors. But for certain exceptions such as InvalidArgumentException, I would not catch it and let the handler test if(is_a($exception, 'InvalidArgumentException')) and handle all of them with an error page if that's what I want.

                3. This custom exception handler regardless can be kept in case to handle any other exceptions that are mistakenly uncaught, never allowing the user to see an uncaught exception msg.

                  If they don't require handling then they're not exceptions - which are, by definition, exceptional, and mean that the code throwing the exception is unable, through circumstances beyond its control, to proceed in any meaningful way. It gets caught at the point where meaningful progress can be made.

                  if(is_a($exception, 'InvalidArgumentException'))

                  [man]is_a[/man] is deprecated as of PHP 5.0.0.

                  In Python exceptions are commonly used for basic flow control.

                  PHP is not Python. Python's exceptions are far simpler and their construction doesn't involve things like building a stack trace. As such, PHP's exceptions are more heavyweight than ordinary flow control structures. (Python even throws a SystemExit exception simply to exit the program.)

                  Keep an exception handler around to swallow uncaught exceptions, but uncaught exceptions in PHP would imply that the program is broken (which is why a stack trace is included in the Exception). It's no accident that what the exception handler receives is described as a PHP Fatal Error; it's equivalent to the Windows dialogue saying "This program has performed an illegal function and will be shut down" (see this note in the manual page for set_exception_handler().)

                  So yes, you would want to be notified of an uncaught exception so that you can fix it, either by catching and sensibly handling it after it has been thrown, or by making it impossible for the circumstances that caused it to be thrown to occur in the first place.

                    Thanks for all the good info.

                    So how do you guys handle invalid arguments? Do you catch it within the function/class or do you just throw the exception? Like a lot of my situations, I would want execution to halt and then I would show an error msg or page and then somehow notify admin. Is that exception worthy or use trigger_error()?

                      One model I use in typical circumstances:

                      The public interface of a method should document what constitutes a valid argument. Given that, the caller should be written to make sure that the argument is valid before passing it to the method.

                      If the caller fails to do so, and the method receives invalid input (i.e. something that it has not been written to handle), then it throws an exception. It probably won't be the caller that catches it (because if it could be written to handle the exception it could be written to avoid passing invalid data in the first place), but something higher up (possibly something in whatever third-party code was using the library in which my method appeared).

                        Write a Reply...