PHP Exceptions

Exceptions are a mechanism in PHP (and many other programming languages) that allow you to handle errors and exceptional situations in a more controlled and structured way. When an error or exceptional condition occurs, an exception is thrown, and you can catch and handle that exception in your code.

Here's a basic overview of how exceptions work in PHP:

Throwing an Exception:

You can throw an exception using the `throw` keyword followed by an instance of a class that extends the base `Exception` class or one of its subclasses.

php
<?php
function divide($numerator, $denominator) {
    if ($denominator === 0) {
        throw new Exception("Cannot divide by zero");
    }
    return $numerator / $denominator;
}

try {
    echo divide(10, 0);
    } catch (Exception $e) {
        echo "Caught exception: " . $e->getMessage();
    }
?>

In this example, the `divide()` function throws an exception when the denominator is zero. The `catch` block catches the exception, and you can access information about the exception using the `$e` variable.


Custom Exception Classes:

You can create your own custom exception classes by extending the base `Exception` class. This allows you to create more specific exception types for different scenarios.

```php
<?php
class MyCustomException extends Exception {
    // additional methods and properties specific to your exception
}

function process($data) {
    if ($data === null) {
        throw new MyCustomException("Data cannot be null");
    }
}

try {
    process(null);
} catch (MyCustomException $e) {
    echo "Caught custom exception: " . $e->getMessage();
}
?>

Multiple Catch Blocks:

You can have multiple `catch` blocks to handle different types of exceptions.

php
<?php
try {
    // code that might throw exceptions
} catch (MyCustomException $e) {
    echo "Caught custom exception: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught generic exception: " . $e->getMessage();
}
?>

Finally Block:

You can also include a `finally` block after the `catch` blocks. The code in the `finally` block will be executed regardless of whether an exception was caught or not.

php
<?php
try {
    // code that might throw exceptions
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
} finally {
    echo "Finally block executed.";
}
?>

Using exceptions allows you to separate normal program flow from error handling logic, making your code more readable and maintainable.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext