Exceptions in PHP are a way to handle error conditions in a script or application in a more elegant and controlled way compared to traditional error handling techniques using functions like `error_reporting()` and `set_error_handler()`.
1. Basics of PHP Exceptions:
Exceptions are represented as objects in PHP, primarily as instances of the Exception class or a subclass thereof.
To throw an exception, you use the throw statement. Once thrown, an exception can be caught using a try...catch block.
Example:
try {
throw new Exception("An error occurred!");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
2. Properties and Methods of the Exception Class:
3. Multiple Catch Blocks: You can catch different types of exceptions using multiple catch blocks.
try {
// some code
} catch (FirstTypeException $e) {
// Handle FirstTypeException
} catch (SecondTypeException $e) {
// Handle SecondTypeException
} catch (Exception $e) {
// Handle generic Exception
}
4. Creating Custom Exceptions: You can create custom exception classes by extending the base `Exception` class.
class CustomException extends Exception { }
try {
throw new CustomException("This is a custom exception!");
} catch (CustomException $e) {
echo 'Caught custom exception: ', $e->getMessage(), "\n";
}
5. The Finally Block: You can also use a `finally` block after the `catch` blocks, which will always execute regardless of whether an exception was thrown.
try {
// some code
} catch (Exception $e) {
// Handle the exception
} finally {
// This code will always execute
echo "Always executed!";
}
6. Rethrowing Exceptions: You can catch and then rethrow an exception, possibly after logging it or performing some other operations.
try {
// some code
} catch (Exception $e) {
// Log the exception or do some other processing
throw $e; // Rethrow the same exception
}
7. Nested Exceptions: You can throw an exception within a catch block, which can be used to indicate a different or higher-level error.
try {
try {
// some code
} catch (Exception $e) {
throw new HigherLevelException("A higher-level error occurred.", 0, $e);
}
} catch (HigherLevelException $e) {
// Handle the higher-level exception
}
Summary:
This is a basic overview of PHP exceptions. For more detailed information and advanced techniques, refer to the PHP documentation.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here