Exceptions
6 min read Quiz at the end
Exceptions handle errors cleanly using try, catch, and finally blocks. When something goes wrong, throw an exception and catch it to show a message or log the error. The finally block always runs for cleanup.
Exceptions // Basic try/catch
try {
$result = 10 / 0;
if (!$result) throw new Exception("Division error");
} catch (Exception $e) {
echo $e->getMessage(); // "Division error"
echo $e->getCode();
echo $e->getFile();
echo $e->getLine();
} finally {
echo "Always runs";
}
// Multiple catch blocks
try {
// risky code
} catch (InvalidArgumentException $e) {
// handle invalid args
} catch (RuntimeException $e) {
// handle runtime errors
} catch (Exception $e) {
// catch all
}
// Custom exception
class ValidationException extends RuntimeException {
public function __construct(string $field, string $msg) {
parent::__construct("$field: $msg", 422);
}
}
throw new ValidationException("email", "Invalid format");
Topic Quiz · 5 questions
Test your understanding before moving on
1. Which keyword throws an exception?
A. error
B. raise
C. throw
D. except
💡 throw new Exception("message") throws an exception in PHP.
2. Which block catches exceptions?
A. handle
B. except
C. error
D. catch
💡 try { } catch (Exception $e) { } is the PHP exception handling syntax.
3. What does the finally block do?
A. Handles errors
B. Runs only on success
C. Always runs after try/catch
D. Logs exceptions
💡 finally runs regardless of whether an exception was thrown.
4. What class do custom exceptions extend?
A. ErrorClass
B. BaseException
C. Exception or a subclass
D. Throwable only
💡 Custom exceptions extend Exception or one of its subclasses.
5. Which method gets the exception message?
A. $e->text()
B. $e->getMessage()
C. $e->getMsg()
D. $e->error()
💡 getMessage() returns the exception message string.
Submit answers