How to use ‘try/catch’ in PHP (with Examples)

'try/catch' in PHP

PHP is one of the most popular programming languages used to develop web applications and APIs. Linux is the system of choice for serving up your PHP code and is also an ideal PHP development environment.

When writing PHP code, you’ll sometimes want to perform a certain action when an error is encountered (rather than just sending the user an error message and halting code execution). This is exactly what try/catch is used for in PHP.

Syntax

try {
    // Code to attempt
} catch (Exception $e) {
    // Code to execute if there's an error
} 
// Execution resumes here, only if there was no error!

Note that:

  • Commented lines begin with //
  • Commented lines will be ignored by PHP, so you can leave notes explaining your code

Finally

finally block can be optionally specified after your catch block. Code in the finally block will always be executed – whether an error was encountered or not:

try {
    // Code to attempt
} catch (Exception $e) {
    // Code to execute if there's an error
} finally {
    // Code to execute regardless of whether there was an error
}
//Execution resumes here, only if there was no error!

Example

try {
    // rand(0, 1) will generate an integer between 0 and 1, inclusive
    $val = rand(0, 1);
    // If $val is equal to 0, throw an error - this gives a 50/50 chance that an error will be thrown when this code is executed
    if($val == 0){
        throw new Exception('Uh Oh! There was an error!');
    }    
} catch (Exception $e) {
    // The Exception class object $e will contain details about the error
    echo 'Caught error with message: ' . $e->getMessage();
} finally {
    echo "There is a 50/50 chance that an error was just thrown.";
}

Conclusion

try/catch is a very useful tool to keep handy when writing PHP, especially while debugging, or if there’s a specific way you need to handle an error.

Click here for more programming tutorials from LinuxScrew!

To view the official documentation for PHP error and exception handling:

https://www.php.net/manual/en/language.exceptions.php

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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