PHP Exceptions

An exception is an object that describes an error or an unexpected situation behaviour of a PHP script.


Exceptions are thrown by many PHP functions and classes.


User defined functions and classes can also throw exceptions.


Instead of stopping the script when an error occurs, you can catch and handle the error.

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
<?php
// Code that might throw an exception
$x = 5;
if ($x > 0) {
throw new Exception("Value must be less than or equal to 0.");
}
?>

Try it yourself

The result will look something like this:

The try...catch Statement


The try-catch statement in PHP is used to handle exceptions that may occur during the execution of a block of code.


It allows you to catch exceptions, manage errors gracefully, and prevent the script from crashing unexpectedly.


Syntax of try-catch Statement


try {
  // Code that may throw an exception
} catch (ExceptionType $e) {
  // Code to handle the exception
}


Below example is show a message when an exception is thrown:

<?php
try {
// Code that may throw an exception
$num = 10;
if ($num > 5) {
throw new Exception("Number is greater than 5");
}
} catch (Exception $e) {
// Handling the exception
echo "Caught exception: " . $e->getMessage(); // Outputs the message of the exception
}
?>

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.

The try...catch...finally Statement


The try...catch...finally statement can be used to catch exceptions.


This structure provides a way to handle exceptions and ensures that certain code always executes, regardless of whether an exception was thrown or not.


Syntax of try...catch...finally


try {
  // Code that may throw an exception
} catch (ExceptionType $e) {
  // Code to handle the exception
} finally {
  // Code that will always run
}


Below example show a message when an exception is thrown and then indicate that the process has ended:

<?php
try {
// Code that may throw an exception
$num = 10;
if ($num > 5) {
throw new Exception("Number is greater than 5");
}
} catch (Exception $e) {
// Handle the exception
echo "Caught exception: " . $e->getMessage();
} finally {
// Code that will always run
echo "<br>Finally block executed.";
}
?>

Try it yourself

Explanation:

  • In this example, the try block checks if $num is greater than 5. Since it is, it throws an exception with the message "Number is greater than 5".
  • The catch block catches the exception and outputs the message "Caught exception: Number is greater than 5".
  • Regardless of whether an exception is thrown or not, the finally block will always execute and print "Finally block executed.".

Below example outputs a string even if an exception was not caught:

<?php
try {
// Code that doesn't throw an exception
$num = 3;
if ($num <= 5) {
echo "Number is less than or equal to 5.";
}
} catch (Exception $e) {
// This block won't be executed since no exception is thrown
echo "Caught exception: " . $e->getMessage();
} finally {
// This block will always run
echo "<br>Finally block executed.";
}
?>

Try it yourself

The Exception Object



In PHP, exceptions are objects of the built-in Exception class (or subclasses of it). An exception object represents an error or an unexpected event that occurs during the execution of a script.


When an exception is thrown, an object of the Exception class is created, which contains useful information about the error, such as the message, code, file, line number, and stack trace.


Syntax


new Exception(message, code, previous)


Parameters:

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


PHP's Exception object provides several useful methods that allow you to get detailed information about the exception:

Method

Description

getMessage()

Returns the exception message.

getCode()

Returns the exception code.

getPrevious()

Returns the previous exception if it exists.

getFile()

Returns the full path of the file in which the exception was thrown

getLine()

Returns the line number where the exception was thrown.

Below example shows output information about an exception that was thrown:

Example
<?php
try {
// Code that may throw an exception
$num = 10;
if ($num > 5) {
throw new Exception("Number is greater than 5");
}
} catch (Exception $e) {
// Handling the exception
$code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo "Exception thrown in $file on line $line: [Code $code]
$message";
}
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.