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...
}
ScottMcGready
  • 1,612
  • 2
  • 24
  • 33
Matt3o12
  • 4,192
  • 6
  • 32
  • 47

1 Answers1

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");
}
Justin ᚅᚔᚈᚄᚒᚔ
  • 15,081
  • 7
  • 52
  • 64