What is Exception in PHP?
One of the ways in which PHP deals with special conditions that change the normal flow of a program (e.g., runtime errors) is to raise exceptions. Along with the built-in Exception class, PHP also has a mechanism of detecting that an Exception has occurred, and doing something useful when it does.
example. Try/Catch Control Flow Statement
try
{
throw new Exception();
}
catch (Exception $e)
{
echo "An exception was raised.";
}
Throughout this book, we will see code that deals with a wide range of Exception subclasses. Most of those subclasses we will make ourselves, though they will be subclasses of those found in the SPL. You might be wondering why we would ever need to subclass Exception (or any of the SPL Exception subclasses) if we can just try/catch Exception to deal with errors in our framework.
Below Example:
try
{
throw new LogicException();
}
catch (ClassDidNotLoadException $e)
{
// runs only if the Exception thrown
// is of type "LogicException"
echo "LogicException raised!";
}
catch (Exception $e)
{
// runs only if an Exception was thrown which
// was not caught by any previous catch blocks
echo "Something went wrong, and we don't know what it was…";
}
As you can see, PHP’s try/catch statement allows us to catch multiple types of Exception. This isn’t really valuable to us when we can only expect one type of Exception to occur, but in a complicated framework of many classes and contexts, it becomes quite valuable in maintaining a stable system.Think of a situation in which we are interacting with a database. A simple record update can fail in a number of contextually separate ways. There could be a problem connecting to the database, missing data preventing successful validation, or even a syntax error in the underlying SQL we send to the database. All of these contexts
can have different Exception subclasses, and can be trapped in the same try/catch statement, with minimal effort. One final benefit of creating many Exception subclasses is that we can respond to the user interface based on what Exception subclass is being thrown. We might want to display different views depending on whether the Exception thrown is caused by a problem in the database, or caused by a problem in the caching classes, and so forth. It is important to remember that any time you see a class instance being thrown that contains the word Exception, it is likely an Exception subclass that we have created to signify a specific error. We won’t always cover the code for individual Exception subclasses, but at least we know the reasons for creating them, and that
they resemble the original Exception class.
Post a Comment