How can the issue of having more Exception types in sub-classes than in their parent classes be resolved in PHP?
Issue: When a subclass introduces more Exception types than its parent class, it can lead to inconsistency and confusion in handling exceptions. To resolve this issue, we can create a custom exception class in the parent class that can handle all possible exceptions thrown by both the parent and subclass.
class ParentException extends Exception {}
class ParentClass {
public function someMethod() {
throw new ParentException("An error occurred in ParentClass");
}
}
class SubClass extends ParentClass {
public function someMethod() {
try {
// Code that may throw exceptions
} catch (Exception $e) {
throw new ParentException($e->getMessage());
}
}
}