Menu
Coddy logo textTech

The 'try...catch' Block

Part of the Logic & Flow section of Coddy's PHP journey — lesson 53 of 68.

When your PHP code encounters problems that could cause it to crash, you need a way to handle these situations gracefully. The try...catch block provides a structured approach to deal with exceptions - special error objects that represent serious problems in your code.

The try block contains code that might fail or throw an exception. If an exception occurs within this block, PHP immediately stops executing the remaining code in the try block and jumps to the corresponding catch block. The catch block handles the exception, allowing your script to continue running instead of crashing.

<?php
try {
    // Code that might throw an exception
    $result = riskyFunction();
    echo "Success!";
} catch (Exception $e) {
    // Handle the exception
    echo "An error occurred: " . $e->getMessage();
}
?>

The catch block receives an Exception object that contains information about what went wrong. You can access the error message using the getMessage() method. This approach prevents your entire script from stopping when something goes wrong, giving you control over how errors are handled and what your users see.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You will receive one input: a number representing an age value. The input might be a negative number, which would be invalid for an age.

Read the input, convert it to an integer, and create a try...catch block. Inside the try block, check if the age is negative. If it is negative, throw a new Exception with the message "Age cannot be negative". If the age is valid (zero or positive), print "Valid age: " followed by the age value.

In the catch block, handle the exception by printing "Error: " followed by the exception message using the getMessage() method.

Input format: One line containing an integer (example: 25 or -5)

Expected output:

  • If the age is valid: Valid age: followed by the age value
  • If the age is negative: Error: Age cannot be negative

Cheat sheet

The try...catch block handles exceptions in PHP, preventing scripts from crashing when errors occur.

Basic syntax:

<?php
try {
    // Code that might throw an exception
    $result = riskyFunction();
    echo "Success!";
} catch (Exception $e) {
    // Handle the exception
    echo "An error occurred: " . $e->getMessage();
}
?>

The try block contains potentially problematic code. If an exception occurs, PHP jumps to the catch block, which receives an Exception object. Use getMessage() to access the error message.

You can manually throw exceptions using:

throw new Exception("Custom error message");

Try it yourself

<?php
// Read input
$age = intval(fgets(STDIN));

// TODO: Write your code below
// Create a try...catch block to validate the age


?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow