Error Handling and Runtime Exceptions
Try/Catch
Section titled “Try/Catch”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();}Throwing Exceptions
Section titled “Throwing Exceptions”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"}Exception Methods
Section titled “Exception Methods”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}Multiple Catch Blocks
Section titled “Multiple Catch Blocks”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.
Common Exception Types
Section titled “Common Exception Types”| Exception | Use Case |
|---|---|
Exception | General errors |
InvalidArgumentException | Invalid function arguments |
RuntimeException | Errors during execution |
PDOException | Database errors |
TypeError | Wrong type passed to function |
function setAge(int $age) { if ($age < 0) { throw new InvalidArgumentException("Age cannot be negative"); }}Finally Block
Section titled “Finally Block”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}Example
Section titled “Example”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"}