php

How to Throw Exceptions in PHP?

PHP is a programming language that allows developers to write code that can execute on web servers to produce dynamic web pages. One important feature of PHP is the ability to throw exceptions, which are error conditions that can occur during the execution of a program.

In this article, we will explore the basics of throwing exceptions in PHP and provide examples of how to use them in your code.

What are Exceptions?

Exceptions are a vital aspect of any programming language as they enable developers to handle runtime errors gracefully terminating the program or running alternative code that resolves the issues. In PHP, just like any other language, you can throw exceptions using built-in functions or custom exceptions.

How Do Exceptions Work in PHP?

Whenever an error is encountered during the execution of the program, it terminates the script and prints the error message on the screen, which is not a desirable outcome in most cases. However, with the use of exceptions, it is possible to handle errors gracefully and continue with the program’s execution. The moment an exception is thrown, the program is momentarily put on hold while the nearest catch block that can deal with the issue takes over.

How to Throw Exceptions in PHP?

To throw exceptions in PHP, you can use the following methods:

1: Using throw Keyword

When an issue occurs while the program is running, exceptions that are objects, are thrown in PHP. To throw an exception in PHP, you first need to create an exception object using the “throw” keyword. The most basic form of throwing an exception is as follows:

throw new Exception("Error message");

Let’s look at an example:

<?php
function checkNum($num) {
  if($num>5) {
    throw new Exception("Value must be lesser than 5");
  }
  return true;
}
checkNum(6);
?>

The provided code implements a function checkNum($num), which accepts a number as input and throws an exception with the message “Value must be less than 5” if the input number exceeds 5. The checkNum() function is then used by the code with the input 6, which results in an exception because 6 is greater than 5. Due to the absence of a try-catch block, the code exits with an uncaught exception error.

Output

2: Using try-catch Statement

PHP provides a try-catch statement to handle exceptions in the code. Code that might raise exceptions is contained in the try block and the catch block processes and deals with the exception. If an exception is not caught within the catch block, it propagates up the call stack, and if it reaches the top of the stack, it terminates the program.

The following syntax shows the try-catch usage in PHP code.

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

In the below example, you can learn how to utilize try-catch statements in PHP.

<?php
function div($num1, $num2) {
    if($num2 == 0) {
        throw new Exception("Cannot divide by zero");
    }
  return $num1 / $num2;
}
try {
    echo div(2, 0);
} catch(Exception $e) {
    echo "Error: Division by zero.";
}
?>

The above code defines a method called div($num1, $num2) that divides two numbers, however if the second input $num2 is zero, it throws an exception with the message “Cannot divide by zero”. A try-catch block is then used in the code to handle exceptions. The div() function is called with the arguments 2 and 0, which results in the exception. Error: Division by Zero is repeated by the catch block after it captures the exception.

Output

3: Using try-catch-finally

The finally block was introduced in PHP 5.5 and later versions as a mechanism to execute cleaning code after a try-catch block, whether or not an exception was thrown.

Code that might raise an exception can be placed in a try block. Any exceptions that are thrown will be dealt with in the catch block. The finally block is executed following the try and catch blocks, even if an exception was raised. This makes sure that even in the event of an unexpected exception, the finally block’s function is always carried out.

Here is an illustration of how PHP’s try-catch-finally is used:

<?php
function div($num1, $num2) {
    if ($num2 == 0) {
        throw new Exception("Cannot divide by zero.");
    }
    return $num1 / $num2;
}
try {
    echo div(6, 0);
}
catch(Exception $e) {
    echo "Error: Division by zero.";
}
finally {
    echo "Calculation complete.";
}
?>

The above code defines a method called div($num1, $num2) that divides two numbers, however, if the second input $num2 is zero, it throws an exception with the message “Cannot divide by zero”. The try-catch-finally block is then used by the code to take care of exceptions.

The div() function is called with the arguments 6 and 0, which results in the exception. Error: Division by Zero is repeated by the catch block after it captures the exception. Following that, the finally block is carried out, echoing “Calculation complete”. This block is often used for cleanup or finalization operations and is done whether or not an exception was thrown.

Output

4: Using Custom Exception Class

By modifying the default Exception class in PHP, you can also develop your own exception classes. It will contain all the exception class’s original characteristics, but you can give it your own unique functions.

For instance, let’s say you want to designate an exception for situations where a user submits an incorrect value. You can do this by creating a new class that modifies the Exception class, as follows:

class InvalidInputException extends Exception{}

A new class called InvalidInputException that extends the Exception class is being developed. You can add your own unique properties and methods on top of the properties and methods that this new class inherits from the Exception class.

The use of custom exception classes in PHP is shown below:

<?php
  class customException extends Exception {
    public function error_message() {
      $error_msg = 'Error caught on line '.$this->getLine().$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }

  $email = "[email protected]";

  try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      throw new customException($email);
    }
  } catch(customException $e) {
    echo $e->error_message();
  }
?>

The above code creates an extension of PHP’s built-in Exception class called customException. The error message() method of the customException class returns a custom error message that includes the line number where the exception was caught, the parent Exception class’s error message, and a message that the supplied email address is invalid.

A try-catch block is then used to check an email address using the filter_var() function, and if it is invalid, it throws a customException with the invalid email as the argument. The error_message() function of the customException class is used in the catch block to catch the customException explicitly and replay the custom error message.

Output

5: Through Multiple Exceptions

You can simultaneously check different conditions by employing several exceptions. You can use a switch, several if-else code blocks, or numerous exceptions to do it. Remember that each of these exceptions may employ a different class and provide distinct error messages.

Let’s look at an example:

<?php
  class customException extends Exception {
    public function error_message() {
      $error_msg = 'Error caught on line '.$this->getLine().$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }
  $email = "[email protected]";
  try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      throw new customException($email);
    }
    if(strpos($email, "ex") !== FALSE) {
      throw new Exception("$email contains'ex'");
    }
  }
  catch(customException $e) {
    echo $e->error_message();
  }
  catch(Exception $e) {
    echo $e->getMessage();
  }
?>

The above code creates a custom exception class, which has an error_message() method. It checks for email validity using filter_var() and throws a custom exception if invalid. It also checks if the email contains “ex” using strpos() and throws a built-in exception if true. Two catch blocks handle the exceptions, one for the custom exception with a custom message and another for all other exceptions using the getMessage() method.

Output

6: Rethrowing an Exception

Within the catch() block, you can throw the exception twice. Such a script is intended to conceal system faults from web application users. Users shouldn’t care about system errors, even though the coder may wish to be aware of them. You can re-throw the exception to modify the message if you want the error message to be more user-friendly.

Let’s look at an example:

<?php
  class customException extends Exception {
    public function error_message() {
      $error_msg = $this->getMessage().' is not a valid e-Mail address.';
      return $error_msg;
    }
  }
  $email = "[email protected]";
  try {
    try {
      if(strpos($email, "ex") !== FALSE) {
        throw new Exception($email);
      }
    } catch(Exception $e) {
      throw new customException($email);
    }
  } catch(customException $e) {
    echo $e->error_message();
  }
?>

The above code example checks to see if the email address given contains the string example as its value. If a string is found, an exception is fired again. The class customException() is created as an addition to the original class and inherits all of its methods and properties. There is now a function called error_message(). This function returns an error message in the case of an incorrect email address. The word “ex” appears in the string $email, which is a legitimate email address.

Another try() block is contained in the try() and is utilized to rethrow an exception. Since the sample string value is present in the $email variable, an exception is raised. A custom exception is then thrown once the exception is caught. This exception shows a clear error message. If the exception’s current try() block does not have a catch() block, it may explore higher levels for one.

Output

7: Top-Level Exception Handler

The set_exception_handler() function creates a user-defined function that is designed to handle each uncaught exception. Let’s look at an example:

<?php
function myException($exception) {
  echo "Exception: " . $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('This is an uncaught Exception');
?>

In this example, the myExceptionHandler() function is defined as the custom exception handler. It simply prints the message of the exception that was thrown. Then, the set_exception_handler() function is called with the name of the custom exception handler function as an argument. Finally, an exception is thrown to trigger the custom exception handler, which will display the exception message when run.

Output

Finally, it is worth noting that throwing exceptions can have a negative impact on a program’s performance if not used correctly. To avoid this, it is necessary to throw exceptions only when necessary and handle them gracefully to ensure a reliable and efficient program.

Conclusion

In PHP, throwing exceptions is crucial for dealing with unforeseen mistakes that may arise while a program is being executed. To throw exceptions in PHP, you can define a custom exception class, throw an instance of that exception, wrap the code that might cause an exception in a try block, handle the exception in a catch block, or finally add any cleanup code in a finally block. By following these steps, you can ensure that your PHP scripts are resilient to errors and able to recover quickly from any unexpected situations.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.