PHP Exceptions
What is PHP Exceptions?
An exception is an unwanted or unexpected event that occurs during the execution of a PHP script.
Exceptions are thrown by many PHP functions and classes
(if an unexpected situation arises, such as invalid data).
When an exception is thrown, it can be caught by a block of code (usually a try...catch
block) with proper
error handling. If an exception is not caught, it will be handled by
the default exception handler and often results in a fatal error and script
termination.
PHP uses the following keywords for exception handling:
throw- This keyword is used to throw exceptions.try- This keyword is used to create atry...catch, or atry...catch...finallystatement.catch- This keyword is used to handle exceptions that are thrown by the code in a precedingtryblock.finally- This keyword is used intry...finallyandtry...catch...finallyto run a block of code whether or not an exception occurred.
PHP throw Keyword
The throw
keyword is used to throw an exception.
If an exception is NOT caught, a fatal error will occur with an "Uncaught Exception" message, and the script is terminated.
Here we throw an exception without catching it:
Example
<?php
function divide($x, $y) {
if($y == 0) {
throw new Exception("Cannot divide by zero.");
}
return $x
/ $y;
}
echo
divide(5, 0); // code that can throw an exception
echo 'Hello';
?>
Try it Yourself »
The result will look something like this:
Fatal error: Uncaught Exception: Division by zero in
C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4
PHP try...catch Keyword
Here we use the
try...catch keyword, to catch the exception/error
from the example above and continue the
script.
Syntax
try {
code that can throw an exception
} catch(Exception $e) {
code to run when an exception is caught
}Example
Display a message when an exception is thrown, and continue script:
<?php
function divide($x, $y) {
if($y == 0) {
throw new Exception("Cannot divide by zero.");
}
return $x
/ $y;
}
try {
echo divide(5, 0); // can throw an exception
} catch(Exception $e) {
echo 'Error: ' .
$e->getMessage();
}
echo '<br>Hello';
?>
Try it Yourself »
The catch block indicates what type of exception should be caught and the name of the
variable which can be used to access the exception. In the example above, the type of
exception is Exception and the variable name is $e.
PHP try...catch...finally Keyword
The try...catch...finally keyword can be used to catch exceptions.
The code in the
finally block will run regardless of
whether an exception was caught.
Syntax
try {
code that can throw an exception
} catch(Exception $e) {
code to run when an exception is caught
} finally {
code that always runs regardless of exception
}Example
Display a message when an exception is thrown, and then indicate that the process is complete:
<?php
function divide($x, $y) {
if($y == 0) {
throw new Exception("Cannot divide by zero.");
}
return $x
/ $y;
}
try {
echo divide(5, 0); // can throw an exception
} catch(Exception $e) {
echo 'Error: ' . $e->getMessage();
}
finally {
echo '<br>Process complete.';
}
?>
Try it Yourself »
PHP Exception Object
The Exception Object contains information about the unexpected behaviour the function encountered.
Syntax
new Exception(message, code, previous)
Parameter Values
| Parameter | Description |
|---|---|
| message | Optional. A string describing why the exception was thrown |
| code | Optional. An integer that can be used to easily distinguish this exception from others of the same type |
| previous | Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter |
Methods
When catching an exception, the following table shows some of the methods that can be used to get information about the exception:
| Method | Description |
|---|---|
| getMessage() | Returns a string describing why the exception was thrown |
| getPrevious() | If the exception was triggered by another one, this method returns the previous exception |
| getCode() | Returns an integer which can be used to identify the exception |
| getFile() | Returns the absolute path to the file where the exception occured |
| getLine() | Returns the line number of the code that threw the exception |
The following example uses several of the Exception methods to get more information about the exception that was thrown:
Example
Output more information about the exception that was thrown:
<?php
function divide($x, $y) {
if($y == 0) {
throw new Exception("Cannot divide by zero.");
}
return $x
/ $y;
}
try {
echo divide(5, 0);
} catch(Exception $e)
{
$file = $e->getFile();
$line = $e->getLine();
$code = $e->getCode();
$message = $e->getMessage();
echo
"Exception thrown in $file on line $line: [Code $code] $message";
}
?>
Try it Yourself »
Complete Exception Reference
For a complete reference, go to our Complete PHP Exception Reference.
The reference contains descriptions and examples of all Exception methods.