Skip to content

Error Handling and Runtime Exceptions

Use try/catch to handle errors gracefully instead of crashing:

try {
// Code that might fail
$result = riskyOperation();
} catch (Exception $e) {
// Handle the error
echo "Error: " . $e->getMessage();
}

Use throw to signal an error:

function divide($a, $b) {
if ($b === 0) {
throw new Exception("Cannot divide by zero");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo $e->getMessage(); // "Cannot divide by zero"
}

Exceptions provide useful information about what went wrong:

try {
throw new Exception("Something failed", 500);
} catch (Exception $e) {
echo $e->getMessage(); // "Something failed"
echo $e->getCode(); // 500
echo $e->getFile(); // File where exception was thrown
echo $e->getLine(); // Line number
}

Handle different exception types separately:

try {
// Code that might throw different exceptions
$data = fetchData();
} catch (InvalidArgumentException $e) {
echo "Invalid input: " . $e->getMessage();
} catch (RuntimeException $e) {
echo "Runtime error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
}

Order matters - catch specific exceptions first, then general ones.


ExceptionUse Case
ExceptionGeneral errors
InvalidArgumentExceptionInvalid function arguments
RuntimeExceptionErrors during execution
PDOExceptionDatabase errors
TypeErrorWrong type passed to function
function setAge(int $age) {
if ($age < 0) {
throw new InvalidArgumentException("Age cannot be negative");
}
}

Code in finally always runs, whether an exception occurred or not:

try {
$file = fopen("data.txt", "r");
// Process file
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
fclose($file); // Always close the file
}

function getUser($id) {
if ($id <= 0) {
throw new Exception("Invalid user ID");
}
// Simulate database lookup
$users = [1 => "John", 2 => "Jane"];
if (!isset($users[$id])) {
throw new Exception("User not found");
}
return $users[$id];
}
try {
$user = getUser(5);
echo "Hello, $user";
} catch (Exception $e) {
echo "Error: " . $e->getMessage(); // "User not found"
}