PHP: Try and Catch me if you can!

Erland Muchasaj
4 min readNov 6, 2023

The importance of error handling in PHP

Introduce the importance of error handling in PHP
Introduction to error handling in PHP

Error handling is a critical aspect of software development, and in PHP, we have powerful tools to help us manage unexpected issues gracefully. You can throw and also catch any exception that might happen in your application.

Unexpected errors that occur during the code execution are called exceptions. These can happen in multiple scenarios such as: reading a file that does not exist, trying to connect to a DB with wrong credentials, dividing by 0, etc. Instead of breaking the script you can handle them with a catch block, this is also known as exception handling.

Building blocks of Try/Catch.

  • The try block should contain code that can throw an exception.
  • The catch block should contain code to handle the exception.
  • The finally (optional) block should contain code that is always executed, regardless of whether an exception is thrown.

Basic Try-Catch Block.

The try and catch blocks are PHP's way of handling exceptions. An exception is an error that occurs during the execution of your code. Using these blocks, you can gracefully handle exceptions and provide meaningful feedback to users.

Let’s start with a simple example:

simple try/catch block

What you do is you wrap any part of the code that you think will throw an error and you handle it in the catch block.

Of course, you can also manually throw any error using the keyword throw.

Handling multiple exceptions

Try statement can have multiple catch exceptions and each of them handles a specific type of error. When a try...catch statement has multiple catch blocks, the order of exception should be from specific to generic.
The last catch block should contain the code for handling the most generic exception. By doing this, the try...catch statement can catch all the exceptions.

Handling multiple exceptions

PHP 8 introduced union types, allowing us to specify that a parameter or return value must be one of several types. This feature is incredibly useful when handling multiple exceptions.

Handling multiple exceptions with union types

In this example, we catch either a ArgumentCountError or an DivisionByZeroError or Exception. Using union types, you can create cleaner and more concise code when dealing with different exception types.

The Finally Block

In addition to try and catch, PHP provides the finally block. The code in the finally block will always execute, regardless of whether an exception was thrown. This is particularly useful for cleanup tasks.

The final handle will always execute

The finally block ensures that you can release resources, close connections, or perform any necessary cleanup operations, no matter what happens in the try and catch blocks.

Exceptions without error handling.

As of PHP 8.0, the variable name for the caught exception is optional and can be omitted like this:

Try block without exception handling.

This is useful when you just want to wrap a code inside a try block so that it won't stop the code from execution. An example of this would be when you try to send your logs to an external service but you don't care if there is an error, or another use case would be to handle legacy code.

Caution!

When handling error exceptions in a function you have also try/catch/finally be careful of the return type.

<?php

function handleException(): string
{

try {
throw new Exception('Hello World');
} catch (Exception $e) {
return 'caught';

} finally {
return 'finally';
}

return 'Finished';
}

echo handleException(); // => finally

Finally will always run, even if we have a return inside the catch, or even if we re-throw the error again, the final block will be executed, and the last part outside the try catch won’t.

PS: this is applicable only when we return from within the finally{} block.

/**
* @throws Exception
*/
function handleException(): void
{

try {
throw new Exception('Hello World');
} catch (Exception $e) {
echo 'Caught, ';

} finally {
echo 'Finally, ';
}

echo 'Finished, ';
}



echo handleException(); // => Caught, Finally, Finished.

In this case, all the blocks will be executed.

Conclusion

Exception handling is an essential skill for PHP developers. The try and catch blocks, union types, and the finally block provides robust mechanisms for managing errors and exceptions in your code. By following best practices and exploring advanced techniques, you can create more reliable and maintainable PHP applications. So, go ahead, embrace the power of exception handling in PHP, and remember: Try and Catch Me If You Can! 😃 🏃

Feel free to Subscribe for more content like this 🔔, clap 👏🏻 , comment 💬, and share the article with anyone you’d like

And as it always has been, I appreciate your support, and thanks for reading.

--

--