PHP › Error & Exception Handling
How does a try catch block work in PHP, and how do you catch and handle a specific exception that might be thrown?
BeginnerAnswer
A try catch block lets you wrap code that might throw an exception inside a try section, and if an exception occurs, execution immediately jumps to a matching catch block that specifies the type of exception it handles, letting you respond to that specific error condition, such as displaying a user friendly message or logging the issue, without the entire script crashing due to an unhandled exception.
try {
$data = json_decode($jsonString, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Invalid JSON: ' . $e->getMessage();
}Real-world example An API endpoint that parses incoming JSON data wraps the parsing logic in a try catch block, gracefully returning a clear error message to the client if the submitted JSON is malformed, rather than the entire request failing with an unhandled error.