- PHP Exceptions
- Throwing an Exception
- Example
- The try. catch Statement
- Syntax
- Example
- The try. catch. finally Statement
- Syntax
- Example
- Example
- The Exception Object
- Syntax
- Parameter Values
- Methods
- Example
- Complete Exception Reference
- PHP throw Exception
- Introduction to the Exception class
- The throw statement
- Throwing an exception example
- PHP built-in exception classes
- Summary
PHP Exceptions
An exception is an object that describes an error or unexpected behaviour of a PHP script.
Exceptions are thrown by many PHP functions and classes.
User defined functions and classes can also throw exceptions.
Exceptions are a good way to stop a function when it comes across data that it cannot use.
Throwing an Exception
The 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.
If an exception is not caught, a fatal error will occur with an «Uncaught Exception» message.
Lets try to throw an exception without catching it:
Example
function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>
?php
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 thrown in C:\webfolder\test.php on line 4
The try. catch Statement
To avoid the error from the example above, we can use the try. catch statement to catch exceptions and continue the process.
Syntax
Example
Show a message when an exception is thrown:
function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>
?php
try echo divide(5, 0);
> catch(Exception $e) echo «Unable to divide.»;
>
?>
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 .
The try. catch. finally Statement
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.
Syntax
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
Show a message when an exception is thrown and then indicate that the process has ended:
function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>
?php
try echo divide(5, 0);
> catch(Exception $e) echo «Unable to divide. «;
> finally echo «Process complete.»;
>
?>
Example
Output a string even if an exception was not caught:
function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>
?php
try echo divide(5, 0);
> finally echo «Process complete.»;
>
?>
The Exception Object
The Exception Object contains information about the error or unexpected behaviour that the function encountered.
Syntax
Parameter Values
Parameter | Description |
---|---|
message | Optional. A string describing why the exception was thrown |
code | Optional. An integer that can be used 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 this exception was triggered by another one, this method returns the previous exception. If not, then it returns null |
getCode() | Returns the exception code |
getFile() | Returns the full path of the file in which the exception was thrown |
getLine() | Returns the line number of the line of code which threw the exception |
Example
Output information about an exception that was thrown:
function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero», 1);
>
return $dividend / $divisor;
>
?php
try echo divide(5, 0);
> catch(Exception $ex) $code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo «Exception thrown in $file on line $line: [Code $code]
$message»;
>
?>
Complete Exception Reference
For a complete reference, go to our Complete PHP Exception Reference.
The reference contains descriptions and examples of all Exception methods.
PHP throw Exception
Summary: in this tutorial, you will learn about the Exception class in detail and how to throw a new exception in PHP.
Introduction to the Exception class
When encountering a situation from which you cannot recover, you can throw an exception.
An exception is an instance of the Exception class. Like other PHP objects, you use the new keyword to create an instance of the Exception class.
An Exception object has two main properties: a message and a numeric code. The message describes the exception. The numeric code is optional, which specifies the context for a specific exception.
When you create a new exception, you provide the mesage the optional numeric code. For example:
$exception = new Exception('Invalid username or password', 100);
Code language: HTML, XML (xml)
The Exception object has the getMessage() and getCode() that returns the message and numeric code:
$exception = new Exception('Invalid username or password', 100); $message = $exception->getMessage(); $code = $exception->getCode();
Code language: HTML, XML (xml)
The throw statement
In practice, you rarely assign an exception to a variable. Instead, you raise (or throw) the Exception object using the throw statement:
throw new Exception('Invalid username or password', 100);
Code language: HTML, XML (xml)
The throw statement accepts an instance of the Exception class or the subclass of the Exception class. In fact, it accepts any object that implements the Throwable interface. Note that the Exception class also implements the Throwable interface.
When PHP encounters a throw statement, it immediately halts the code execution. Therefore, the code after the throw statement won’t execute.
Throwing an exception example
The following example defines a function called divide() that uses the the throw statement:
function divide($x, $y) < if (!is_numeric($x) || !is_numeric($y)) < throw new InvalidArgumentException('Both arguments must be numbers or numeric strings'); > if ($y == 0) < throw new Exception('Division by zero, y cannot be zero'); > return $x / $y; >
Code language: PHP (php)
How the define() function works.
- First, throw the InvalidArgumentException exception if $x and $y are not numbers or numeric strings.
- Second, throw the division by zero exception if $y is zero.
- Third, return the division of $x and $y .
PHP built-in exception classes
The standard PHP library (SPL) provides many subclasses of the Exception class. For example, you can use the InvalidArgumentException when an argument of a function or method is not valid.
The following shows the exception classes in PHP 8.0:
Exception ClosedGeneratorException DOMException ErrorException IntlException JsonException LogicException BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException OutOfRangeException PharException ReflectionException RuntimeException OutOfBoundsException OverflowException PDOException RangeException UnderflowException UnexpectedValueException SodiumException
Code language: plaintext (plaintext)
Summary
- An exception is an instance of the Exception class that implements the Throwable interface.
- Use the throw statement to raise an exception. The throw statement accepts an exception object that implements the Throwable interface.