Catching an exception in PHP
Whenever you use code that may throw exceptions, wrap the code in a try block and catch any exceptions in a catch block. This structure is similar to an if . . . else conditional statement, except that it uses try and catch instead of if and else. The basic structure is as follows:
try {
// code that might throw exceptions
} catch (Exception $e) {
// handle the exception here
}
The try block could be dozens, even hundreds of lines long. If the code throws an exception, the script jumps immediately to the catch block, where the code decides how to handle the problem. In a development environment, you normally want to display a descriptive error message; but in a production environment, you could redirect the user to a custom error page, while sending an email with details of the problem to the server administrator.
The parentheses after the catch keyword should contain a variable to capture the details of the exception. It is also a good idea to use type hinting to indicate what type of exception you want to deal with. In addition to the basic Exception class, the Standard PHP Library (SPL) defines a number of specialized exception classes that you can use in your class definitions. You can also create your own custom exceptions. Using different types of exceptions enables you to have multiple catch blocks that handle problems in different ways. For example, you may create custom exceptions called InvalidDataException and DatabaseErrorException. You could then handle them like this:
try {
// script to be processed
} catch (InvalidDataException $e) {
// redirect user to input page with appropriate error message
} catch (DatabaseErrorException $e) {
// redirect user to database error page
} catch (Exception $e) {
// handle any generic exceptions
}
The catch block for generic exceptions must come last. Otherwise the type hinting won’t work, as custom exceptions need to extend the built-in Exception class, and therefore belong to the same data type.


LinkBack URL
About LinkBacks
Reply With Quote

LinkBacks Enabled by vBSEO
Bookmarks