Example 1 — Read the Message in a Catch Block
Throw an Exception with a clear message and print it after catching.
<?php
try {
throw new Exception("Username is required");
} catch (Exception $e) {
echo "Error: ", $e->getMessage(), PHP_EOL;
} How It Works
- throw creates an Exception with the given message.
- catch Exception $e receives that object.
- getMessage() returns Username is required.
- We prefix the text with Error: for a simple display.

