Topics Error Handling & File System Exceptions & Error Handling
beginner 12 min read

Exceptions & Error Handling

Try/catch/finally, custom exceptions, error reporting levels, and best practices.

Try/Catch/Finally

try {
\$result = riskyOperation();
if (\$result === false) {
throw new RuntimeException("Operation failed");
}
} catch (RuntimeException \$e) {
echo "Error: " . \$e->getMessage();
} catch (LogicException \$e) {
// Another exception type
} finally {
// Always executed
cleanup();
}

Custom Exceptions

class ValidationException extends RuntimeException {
public function __construct(
string \$message,
private array \$errors = [],
int \$code = 422,
?Throwable \$previous = null,
) {
parent::__construct(\$message, \$code, \$previous);
}
public function getErrors(): array {
return \$this->errors;
}
}

Multiple Catch

PHP 8.0+ supports catching multiple exceptions in one block: catch (A | B \$e)

Examples

<?php
function divide(float $a, float $b): float {
    if ($b === 0.0) {
        throw new InvalidArgumentException('Division by zero');
    }
    return $a / $b;
}
try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo 'Caught: ' . $e->getMessage();
}

Your Notes

Sign in to take notes for this lesson.

Quiz

Error Handling & Files Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.