Thursday, June 3, 2010

Errors vs Exceptions - Definition and Proper Usage for PHP

It is often a confusion for both seasoned and new developers when to properly use an exception handler or an error handler. Sometimes these two are either wrongly understood or used interchangeably. In this article, I will try to provide as much simply insight how they are define and when to use them, particularly in this segment, for PHP.

ERRORS as I have come to define it in PHP are messages thrown to stdout, browser or log file if an error (fatal error), warning or notice condition is met whether if it came from user-level or system-level triggers. They are represented by constants below:
E_ALL - All errors and warnings (doesn't include E_STRICT)
E_ERROR - fatal run-time errors
E_WARNING - run-time warnings (non-fatal errors)
E_PARSE - compile-time parse errors
E_NOTICE - run-time notices (these are warnings which often result from a bug in your code, but it's possible that it was intentional (e.g., using an uninitialized variable and relying on the fact it's automatically initialized to an empty string)
E_STRICT - run-time notices, enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code
E_CORE_ERROR - fatal errors that occur during PHP's initial startup
E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's
initial startup
E_COMPILE_ERROR - fatal compile-time errors
E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
E_USER_ERROR - user-generated error message
E_USER_WARNING - user-generated warning message
E_USER_NOTICE - user-generated notice message

A fatal ERROR when encountered would break further execution of the program or run an exit code. A warning or notice ERROR on the other hand will still execute remaining instructions by default. That behavior however is modifiable using set_error_handler() function and supplying it with an alternative behavior like logging by default instead of echoing and throwing error codes.

Errors are deemed to be PROGRAMMING and CONFIGURATION issues that should be solved immediately when found. These are issues that a developer or programmer can permanently mend in his code and is therefore unnatural to not fix them. Thus, an ERROR can never or should NEVER BE CATCHABLE using the try-catch block.

An EXCEPTION, is defined here.

  • Related Links Widget for Blogspot

No comments: