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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou 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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise5Student Gradebook
Project Setup: Data StructureAdding a New StudentAdding a Grade to a StudentCalculating Student's AverageFinding the Top StudentGenerating a Report Card8Error and Exception Handling
Understanding PHP ErrorsThe 'try...catch' BlockThe 'finally' BlockThrowing an ExceptionCreating a Custom ExceptionUsing a Custom ExceptionRecap: Input Validation3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting