How can exception classes be effectively used in PHP for error handling within classes?

When handling errors within classes in PHP, using exception classes can provide a more structured and organized way to handle different types of errors. By throwing exceptions when an error occurs, we can separate the error-handling logic from the main code flow, making the code more readable and maintainable.

class CustomException extends Exception {}

class MyClass {
    public function doSomething($value) {
        if ($value < 0) {
            throw new CustomException('Value must be greater than 0');
        }
        
        // Rest of the code
    }
}

try {
    $obj = new MyClass();
    $obj->doSomething(-5);
} catch (CustomException $e) {
    echo 'Caught exception: ' . $e->getMessage();
}