Using the throw Keyword for Exception Handling in PHP
This article explains PHP's throw keyword, covering exception fundamentals, the try‑catch mechanism, the exception class hierarchy, and provides detailed code examples demonstrating how to throw and handle both built‑in and custom exceptions for robust error management.
Exception Handling Basics
Before discussing the throw keyword, we review basic concepts of exceptions in PHP: an exception represents an abnormal condition that can interrupt normal execution and be caught by a handler.
1. Definition and Triggering of Exceptions
Exceptions occur during runtime when something goes wrong; throwing an exception stops the current flow and transfers control to a catch block.
2. Capturing and Handling Exceptions
PHP uses try‑catch statements; code that may throw is placed in a try block, and the catch block receives the exception object and executes handling logic.
3. Exception Hierarchy
Exceptions are classes; developers typically define a base exception class and derive specific ones, forming a hierarchy that allows catching at different levels.
Throw Keyword Usage
The general syntax is:
throw expression;where expression evaluates to an exception object.
Example 1
A divide function checks for a zero denominator and throws a new Exception if found. The caller wraps the call in a try‑catch block to display the error message.
function divide($numerator, $denominator) {
if ($denominator === 0) {
throw new Exception("除数不能为零");
}
return $numerator / $denominator;
}
try {
$result = divide(10, 0);
echo "结果为:" . $result;
} catch (Exception $e) {
echo "捕获到异常:" . $e->getMessage();
}Example 2
A custom CustomException class extends Exception , overrides __construct and __toString , and is thrown by processFile when a file does not exist. The exception is caught and printed.
class CustomException extends Exception {
public function __construct($message, $code = 0, Throwable $previous = null) {
parent::__construct($message, $code, $previous);
}
public function __toString() {
return __CLASS__ . ": [{ $this->code }]: {$this->message}";
}
}
function processFile($filePath) {
if (!file_exists($filePath)) {
throw new CustomException("文件不存在");
}
// process file logic...
}
try {
processFile("path/to/nonexistent/file.txt");
} catch (CustomException $e) {
echo $e;
}Conclusion
Understanding and using the throw keyword enables developers to raise exceptions deliberately and handle them gracefully, leading to more robust and maintainable PHP applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.