PHP errors signal code hiccups that need attention
Before we start looking at ways to handle errors in PHP, I wanted to touch on a few topics that beginner programmers tend to get confused. Bugs are normally errors in code that the programmer coded, that produce a result, and that result is not correct.
For example, let’s say that we were creating a power function. If we sent two arguments to the power function, like 2 and 3, we might expect that the power function will raise 2 to the power of 3. If you get 8, the function performed as was intended. If you get something other than 8, for example, 23, the function has a bug.
This type of bug is referred to as a semantical error. The code passes compilation, or interpretation, and it functions, but produces the wrong result. A bug can also be catastrophic, that terminates a program, like forgetting a semi-colon. This type of error is called a syntax error. It will not pass compilation, or interpretation.
An exception may be raised while the code is executing. For example, let’s say that the code is retrieving some data from the database. The server that’s hosting the code loses connection with the database server because of a power failure. There’s no issue with the code. It’s a power failure. So an exception is thrown.
Those exceptions can be caught and handled. These exceptions don’t have to be something as catastrophic as a power failure. You can specify that the function must accept only positive integer values. If a negative number is passed, an exception can be raised and handled.
In the next couple of articles, we’ll look at how to raise and handle exceptions. I know that I preach the MVP model, but error handling will make your life easier. I’ll throw errors into the log file, but we have to know how to generate those errors in the first place in order to throw them in.
DISCOVER HIDDEN TRUTHS WITH MAGIC CONSTANTS IN PHP
PHP – P71:MAGIC CONSTANTS
There are a few magic constants in PHP that we’ll go through: __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__, and __NAMESPACE__.
PHP errors signal code hiccups that need attention
Bugs are normally errors in code that the programmer coded, that produce a result, and that result is not correct.
HANDLING PHP ERRORS PAVES THE WAY FOR RESILIENT CODE
We are programmers and we are great at what we do. Why would we think that we should ever worry about error handling?