In PHP, exceptions are a way to handle errors and exceptional situations that may occur during the execution of a script. When an error occurs that cannot be handled by regular error handling mechanisms like if statements or try-catch blocks, you can throw an exception. Here's how you can work with exceptions in PHP:
You can throw an exception using the throw statement. An exception can be an instance of any class that extends Exception or any built-in PHP exception class.
Example:
function divide($dividend, $divisor) {
if ($divisor === 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
Output:
Caught exception: Division by zero
You can define your own custom exception classes by extending the built-in Exception class or any other exception class.
Example:
class CustomException extends Exception {
public function errorMessage() {
// Error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid email address';
return $errorMsg;
}
}
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new CustomException($email);
}
return true;
}
try {
validateEmail("invalid-email");
} catch (CustomException $e) {
echo "Caught custom exception: " . $e->errorMessage();
}
Output:
Caught custom exception: Error on line ...: invalid-email is not a valid email address
To catch exceptions and handle them gracefully, you can use a try-catch block. Code within the try block is executed, and if an exception occurs, it's caught in the catch block.
Example:
try {
// Code that may throw an exception
throw new Exception("An error occurred");
} catch (Exception $e) {
// Handle the exception
echo "Caught exception: " . $e->getMessage();
}
You can have multiple catch blocks to handle different types of exceptions.
Example:
try {
// Code that may throw exceptions
throw new CustomException("Custom exception");
} catch (CustomException $e) {
// Handle custom exception
echo "Caught custom exception: " . $e->getMessage();
} catch (Exception $e) {
// Handle other exceptions
echo "Caught generic exception: " . $e->getMessage();
}
The finally block is used to execute code regardless of whether an exception is thrown or not. It's useful for cleanup tasks.
Example:
try {
// Code that may throw an exception
throw new Exception("An error occurred");
} catch (Exception $e) {
// Handle the exception
echo "Caught exception: " . $e->getMessage();
} finally {
// This code will always execute
echo "Finally block executed";
}
You can rethrow an exception within a catch block to handle it at a higher level.
Example:
try {
try {
throw new Exception("Inner exception");
} catch (Exception $e) {
// Handle inner exception
throw $e; // Rethrow the exception
}
} catch (Exception $e) {
// Handle outer exception
echo "Caught exception: " . $e->getMessage();
}
PHP provides several built-in exception classes that you can use for specific types of errors:
Exceptions in PHP provide a structured way to handle errors and exceptional situations in your code. By throwing exceptions, catching them with try-catch blocks, and using custom exception classes, you can create robust and error-tolerant applications. They are especially useful for handling unexpected conditions that may arise during script execution.