Catch a exception with interface.
Asked Answered
K

1

9

I have a question about the exception handling in PHP.

I have a lot of exception those means the same: Couldn't found something. All those exception implements the interface (not class) NotFoundException. So to my question: It's possible to check if the exception implement the interface at the catch-block. I know i could change the NotFoundException-interface to a class but some exceptions extended already an other exception. (Example: CategoryNotFoundException extends CategoryException and implements NotFoundException).

Why should I need this interface? When an page is showing and some exception which implements the interface will throw an Error404 should shown. Example:

$userPage = $_GET["page"];
try{
    showPage($userPage);
} catch (){ //How to catch the `NotFoundException` interface?
    showPage("Error404");
} catch (Exception $e){
    showPage("Error500"); //Something is wrong...
}
Karwan answered 14/12, 2012 at 17:21 Comment(0)
O
9

Simply specify the exception class (or interface) you're trying to catch:

try {
    showPage($userPage);
} catch (NotFoundException $e) {
    showPage("Error404");
} catch (Exception $e) {
    showPage("Error500");
}
Oneman answered 14/12, 2012 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.