PHP Try Catch Block with Examples

In this tutorial, we will learn about PHP try catch block with the help of basic syntax and practical examples based on it. Using try-catch blocks is the most common and recommended way to handle exceptions in PHP. Before going to understand about try catch block, let us first understand about what try block in PHP.

Try Block in PHP


A try keyword in PHP is a block of code that might throw an exception. The PHP code that may generate an exception during the execution of program, we place it within the try block. That is, we should place exception generated code (risky code) inside try block.

We should not put the normal code inside try block which might not generate exception. Therefore, normal code should remain outside whenever possible to keep the try block minimal. Let us understand with a simple scenario.

Assume there are three statements inside try block. First statement may occur exception and is on top inside try block. The other two statements are normal and are below the first statement.

If an exception occurred in statement 1, the other two normal statements will not execute. This is because once an exception is thrown, PHP immediately jumps to the matching catch block and the remaining code inside the try block is skipped. Therefore, the length of code inside the try block should be as much as less.

Catch Block in PHP


A catch keyword in PHP is a block of code that handles the exception thrown by the try block. That’s why it is also known as exception handler block.

A catch block always follows a try block and cannot exist on its own. It is used to handle exceptions thrown within that try block. A single try block can have one or more catch blocks to handle different types of exceptions.

Basic Syntax of PHP Try Catch Block


The basic syntax of try-catch block in PHP is as:

try {
   // Code that may cause an exception.
} catch (Exception $e) {
     // Code to handle the exception.
}

In the above syntax:

  • The exception object $e contains detailed error information, such as the error message, error code, file name, line number, stack trace, and related exception data that help us to identify and debug the error.
  • The try block must be followed by at least one catch or finally block.
  • You cannot use a try block without a catch or finally block.
  • No code is allowed between the end of try block and the beginning of catch block.
  • A single try block in PHP can be followed by multiple catch blocks.
  • A finally block cannot come before catch block.

Exception Handling Mechanism using Try Catch Block in PHP


A systematic representation of the try and catch blocks in PHP is shown in the below figure.

Exceptional handling using try catch block in PHP.

The try catch block in PHP is a structured mechanism used to catch and handle exceptions gracefully. When an exception occurs inside the try block, the rest of code or statements inside the try block is not executed. The control of execution is immediately transferred from the try block to the appropriate catch block that handles the exception thrown by the try block.

A catch block acts as an exception handler that accepts a single argument. This argument is a reference to an exception object that can be of the same exception class or a parent (superclass) type such as Exception or Throwable.

If the exception type thrown in the try block matches the type specified in the catch block, the exception is caught and the statements inside the catch block are executed.

If no matching catch block is found, the exception remains unhandled. In this case, PHP invokes its default exception handler, which terminates the script and displays a fatal error message.

In case no exception is thrown inside the try block, all statements in the try block execute normally, the catch block is skipped, and the control of execution continues with the next statement following the try-catch block.

Execution Flow of Try-Catch Block in PHP


Example 1: Exception Occurring after statement 1

<?php
try {
   echo "Statement 1 executed. \n";
   throw new Exception("Exception occurring after statement 1");
   echo "Statement 2 executed. \n";
   echo "Statement 3 executed. \n";
} catch (Exception $e) {
     echo "Statement 4 executed. \n";
}
echo "Statement 5 executed.";
?>

Output:

Statement 1 executed. 
Statement 4 executed. 
Statement 5 executed.

In this example:

  • Inside the try block, statement 1 will execute normally.
  • The throw keyword is used to generate an exception manually. This is because PHP does not automatically throw exceptions for many logical errors, so we must manually generate (throw) exceptions when something goes wrong.
  • new Exception() creates an Exception object, which is immediately thrown by the try block after statement 1.
  • Statement 2 and statement 3 are skipped.
  • The control immediately is transferred to the nearest matching catch block and statement 4 inside the catch block is executed.
  • After executing statement 4, statement 2 and statement 3 inside try block will not execute because the control never goes back to execute the remaining code inside the try block.
  • Once the catch block finishes execution, the control continues with statement 5, which executes normally.

Example 2: Exception occurring after statement 2

<?php
try {
   echo "Statement 1 \n";
   echo "Statement 2 \n";
   throw new Exception("Exception occurring after statement 2. \n");
   echo "Statement 3 \n";
} catch (Exception $e) {
     echo "Statement 4 \n";
}
echo "Statement 5 \n";
?>

Output:

Statement 1 
Statement 2 
Statement 4 
Statement 5

Example 3: No exception occurs inside try block

<?php
try {
   echo "Statement 1 \n";
   echo "Statement 2 \n";
   echo "Statement 3 \n";
} catch (Exception $e) {
    echo "Statement 4 \n";
}
echo "Statement 5 \n";
?>

Output:

Statement 1 
Statement 2 
Statement 3 
Statement 5

In this example:

  • No exception occurs inside try block, so statement 1, statement 2, and statement 3 execute normally.
  • In this case, the catch block is completely skipped because no exception is thrown by try block.
  • Once the execution of try block is completed, the control of execution is immediately passed to statement 5. Statement 5 will execute normally.

Example 4: Exception occurs, but no matching catch block

<?php
try {
    throw new RuntimeException("Runtime error");
} catch (InvalidArgumentException $e) {
     echo "This will not execute";
}
echo "Statement after try-catch";
?>

Output:

PHP Fatal error:  Uncaught RuntimeException: Runtime error

In this example:

  • The try block throws a runtime exception.
  • But the exception object thrown by try block does not match with the exception type of catch block.
  • PHP invokes its default exception handler and stops the execution of script immediately.
  • Code after the try-catch block is not executed normally.

Multiple Catch Block in PHP


In PHP, a single try block can be followed by multiple catch blocks to handle different exception types based on the exception class.

PHP checks the catch blocks in order from top to bottom and executes the first matching catch block. Therefore, more specific exceptions must be caught before generic ones.

The last catch (Exception $e) block usually acts as a fallback. The basic syntax to declare a try block with multiple catch blocks in PHP is as:

try {
  // Code that may throw exceptions.
}
catch (ExceptionType1 $e) {
    // Handle ExceptionType1
}
catch (ExceptionType2 $e) {
   // Handle ExceptionType2
}
catch (Exception $e) {
   // Handle any other exception
}

Example 5: Handling Division by Zero and General Exceptions

<?php
try {
   $x = 10;
   $y = 0;
   $result = $x / $y; // Throws DivisionByZeroError
}
// Multiple catch blocks with more specific to generic exception types.
catch (DivisionByZeroError $e) {
   echo "Error: Cannot divide by zero.";
}
catch (Exception $e) {
   echo "General exception occurred.";
}
?>

Output:

Error: Cannot divide by zero.

In this example:

  • Inside the try block, we divide the number 10 by 0, which is illegal.
  • As a result, PHP throws a DivisionByZeroError.
  • The control of execution is transferred to the first compatible catch block.
  • Once the matching catch block executes, the remaining catch blocks are skipped.
  • Since the exception is handled, the script continues execution normally and does not terminate abnormally.
  • If no catch block is caught the exception, PHP will terminate the script with a fatal error.

Example 6: Multiple Exceptions in a Single Catch Block

PHP 7.1+ added an important feature where you can write multiple exception types in a single catch block using the pipe operator (|). This feature is usually useful when different exceptions require the same handling logic.

<?php
try {
   $x = 10;
   $y = 0;
   if ($y === 0) {
      throw new DivisionByZeroError("Cannot divide by zero");
   }
   echo $x / $y;
}
// Declaration of multiple exception types in a single catch block.
catch (DivisionByZeroError | ArithmeticError $e) {
    echo "Math Error: " . $e->getMessage();
}
?>

Output:

Math Error: Cannot divide by zero

In this example, the variable name ($e) is shared among all exception types declared in the single catch block. PHP allows only one variable for a multi-catch block. You cannot use different variable names for each exception type. All listed exceptions must be compatible types and subclasses of Throwable.

Conclusion

The process of creating an exception object and handing it to the PHP runtime is called throwing an exception in PHP. This exception object contains information such as the exception type (class), error message, error code, file name, line number, and the state of the program where the exception occurred.

After throwing an exception, PHP searches for a block of code that can handle it. This process is known as catching an exception.

A block of code that catches and handles the exception thrown by try block is called exception handler. This entire mechanism is known as exception handling in PHP. We hope you have understood how to handle exception using try catch block in PHP and practiced all examples based on this concept.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.