Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Exception handling is an object- oriented way of responding to abnormal or exceptional situations that can change program flow. Practically speaking, this means avoiding crashing. When there is serious fault, PHP creates what's known as an exception, which is a problem that needs to be dealt with. When an exception is created, it's thrown, which is kind of like telling everybody that there is a problem. To handle an exception, somebody must catch it, which means someone is listening, and dealt with the problem. To prepare for this, I need to surround the code that can throw an exception with a try block, followed by a catch.
This is like me saying, "Let me try to do this action, and if it doesn't work, then I'll deal with the problem." If an exception is thrown and not caught, the program crashes. Not cool. Exceptions are good, as they are a much nicer and logical way of dealing with problems. Instead of just stopping or displaying an error, I've got a chance to gracefully recover, and do something else. I can intentionally throw an exception as well, which is good if a program requires something that is missing, or custom code is out of logical bounds.
To throw an exception, use the throw keyword followed by new, then the Exception class. Within the address example, there are several opportunities to throw an exception. An obvious place to start would be the attempt to load from the database. If a row is not found, then throw an exception. Open the Address class, and navigate to the load method. Following the if, there is a row check. Throw a new exception stating the problem. The first argument is the message.
throw new Exception ('Address_not_found'). Save, then edit the demo. Instead of loading address id 1, attempt to load address id 0, which does not exist. Save, then switch to the browser, and refresh. You will see an uncaught exception. In the next video, I will demonstrate how to catch this exception, then how to customize exceptions to meet your needs.
Get unlimited access to all courses for just $25/month.Become a member