Complete Guide To PHP Exceptions

In this article, we will examine PHP exceptions in-depth, exploring what they are, how they work, and how you can take advantage of them to improve the error handling in your code by using them.

Furthermore, we will discuss some of the best practices when working with PHP exceptions, as well as common pitfalls that you should avoid.

you may have faced errors that prevented your code from running as it should.

There are different types of errors, such as syntax errors, runtime errors, or logic errors.

Managing errors in large code bases can be particularly challenging, especially if you have to deal with a large number of them.

PHP exceptions can be used to deal with errors in a more elegant and organized manner.

Your code can gracefully recover from unwanted errors with exceptions, allowing it to catch and handle errors predictably.



PHP Exceptions – what are they?

A PHP exception is an object that describes a PHP script that has encountered an error or behaved in an unexpected way.

In PHP, a large number of functions and classes throw exceptions when they execute.

There are also exceptions that can be thrown by classes and functions defined by the user.

When a function encounters data that it cannot use, an exception is a good way to stop the function from continuing.


PHP Exception – Throw Statement

An exception can be thrown by a user-defined method or function using the throw statement.

Exceptions prevent code from being executed after they are thrown.

It will cause a fatal error with a message stating Uncaught Exception if the exception is not caught.

Let’s take a look at what happens when an exception is thrown without being caught:

Example: 

<?php function division($numerator, $denominator) { if ($denominator == 0) { throw new Exception("Division by zero"); } return $numerator / $denominator; } echo division(10, 0); ?>

Here is what the result will look like:

Fatal error: Uncaught Exception: Division by zero in /home/mrexamples/.../.../.../execute.php(17) : eval()'d code:6 Stack trace:

PHP try-catch Statement

We can avoid the error in the previous example by using the try-catch statement which will take care of any exceptions and continue the process as soon as an exception occurs.

Syntax

try {
// Code that throws exceptions
} catch(Exception $e) {
// Code that runs when an exception occurs
}

When an exception is thrown, display the message:

Example: 

<?php function division($numerator, $denominator) { if ($denominator == 0) { throw new Exception("Division by zero"); } return $numerator / $denominator; } try { echo division(10, 0); } catch (Exception $e) { echo "Number cannot be divide by zero"; } ?>

As you can see from the catch block, it specifies what type of exception should be caught, as well as the name of the variable that will be used to retrieve the exception.

According to the example given above, the type of exception is Exception and the variable named $e is the name of the exception.


PHP try-catch-finally Statement

Using try-catch-finally simplifies the way in which you can catch and handle exceptions that occur within try blocks.

It also provides a method for executing cleanup code, which should always be run regardless of whether an exception was thrown or not.

The following is a breakdown of how the try-catch-finally statement works:

  • An exception thrown during a program will be placed within the try block.
  • Whenever an exception is thrown, the execution of the code jumps to the catch block immediately.
  • There is a catch block that is responsible for catching the thrown exception and provides a method for handling it. There are different types of exceptions that can be handled by different catch blocks.
  • Whether or not an exception is thrown, the finally block of code contains code that should always be executed. In some cases, this is useful for cleaning up tasks, such as closing database connections or releasing resources in a system.

Syntax

try {
// Code that throws exceptions
} catch(Exception $e) {
// Code that runs when an exception occurs
}finally {
// Whether or not an exception is caught, code runs
}

A message should be displayed when an exception is thrown and then an indication should be displayed as to when the process is completed:

Example: 

<?php function division($numerator, $denominator) { if ($denominator == 0) { throw new Exception("Division by zero"); } return $numerator / $denominator; } try { echo division(10, 0); } catch (Exception $e) { echo "Number cannot be divide by zero"; } finally { echo "<br>Process is completed."; } ?>
Whether or not an exception has been caught, the following string should be displayed:

Example: 

<?php function division($numerator, $denominator) { if ($denominator == 0) { throw new Exception("Division by zero"); } return $numerator / $denominator; } try { echo division(10, 0); } finally { echo "Process complete.";} ?>

The Exception Object

Exception objects are instances of the built-in Exception class.

It contains information about the error or exceptional condition when it encounters a problem during execution.

All exceptions in PHP belong to the exception class.

The exception class also includes several useful methods for dealing with exceptions, including:

MethodOverview
getMessage()It is a method that lets you get the error message associated with the exception.
getPrevious()This method returns the previous exception if the current exception was triggered by another exception. Otherwise, it returns null.
getCode()It will give you the error code.
getFile()This method returns a string that contains the full path of the file from which the exception was thrown.
getLine()This is a method that returns the line number of the code line that threw the exception.

As an example, let’s output information about a thrown exception in the following code:

Example: 

<?php function division($numerator, $denominator) { if ($denominator == 0) { throw new Exception("Division by zero"); } return $numerator / $denominator; } try { echo division(10, 0); } catch (Exception $e) { $file = $e->getFile(); $line = $e->getLine(); $code = $e->getCode(); $message = $e->getMessage(); echo "The file in which exception thrown in $file on line number $line: [Code $code] $message"; } ?>

Example Explanation:

Above example defines a function named division that takes two parameters, $numerator and $denominator, and performs a division operation by dividing the numerator by the denominator. However, before performing the division, the function checks if the denominator is equal to zero. If it is, the function throws an exception with the message Division by zero.

Then a try-catch block is used to call the division function with the arguments 10 and 0. Since the denominator is zero, the function throws an exception, which is caught by the catch block.

Inside the “catch” block, the Exception object is captured and its properties such as file, line, code, and message are accessed using the methods getFile(), getLine(), getCode(), and getMessage(), respectively. These properties provide information about the exception that occurred.

Finally, the code prints a customized error message using the information obtained from the “Exception” object.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *