Exception handling is almost similar in all programming languages. It changes the normal flow of the program when a specified error condition occurs, and this condition is known as exception.
PHP offers the following keywords for this purpose:
This is the block where the code that is likely to have an exception is typed. If the code has exceptions during runtime, the exception is caught and corrected in the catch block. The try block
is usually used with the finally
or the catch
block. A try block is usually used together with one or many catch blocks in a program.
Whenever an exception is thrown in the try block
of a PHP program, a code in the catch block
is executed in an attempt to handle the exception. The catch block
cannot exist on its own. Instead, it works together with the try block
.
The throw keyword is used to throw exceptions in a PHP program. It also allows listing all the exceptions thrown by a particular function and cannot be handled. The throw keyword cannot be used without a catch block
.
The finally block
is used in PHP clean-up activity. This block contains the core of the code and is responsible for its execution. This block can be used as a catch block
and is always executed even if an exception is not handled.
throw
statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed. To avoid the error from the example above, we can use the try...catch
statement to catch exceptions and continue the process.
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
}
Example :
Output : Unable to divide.
The try...catch...finally
statement can be used to catch exceptions. Code in the finally
block will always run regardless of whether an exception was caught. If finally
is present, the catch
block is optional.
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
} finally {
code that always runs regardless of whether an exception was caught
}
Example :
Output : Unable to divide. Process complete.
Output a string even if an exception was not caught:
Output : Process complete.