PHP Exception Handling
Syntax
try {
// code block to be monitored for exception
} catch (Exception $e) {
// code to handle the exception
}
Example
$num1 = 10;
$num2 = 0;
try {
if ($num2 === 0) {
throw new Exception('Division by zero.');
} else {
$result = $num1 / $num2;
echo "Result: " . $result;
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Output
Error: Division by zero.
Explanation
The try
block contains the code that may generate an exception. The catch
block contains the code to be executed when an exception occurs. The Exception
class is used to define custom exceptions.
In the example above, a message is thrown if the divisor is zero. Since num2
is 0, an error is generated and the message is displayed using the getMessage()
function.
Use
Exception handling is used to handle errors that occur during program execution. It allows the programmer to gracefully handle errors and prevent the program from terminating prematurely.
Important Points
- Exceptions are thrown using the
throw
statement - Exceptions are caught using the
try
andcatch
blocks - The
Exception
class is used to define custom exceptions - Exception handling allows for graceful error handling and prevents program termination
Summary
PHP exception handling allows for graceful error handling by catching exceptions that may occur during program execution. The code that may generate an exception is placed in a try
block and the code to be executed when an exception occurs are placed in a catch
block. The Exception
class is used to define custom exceptions.