Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch a exception with interface.

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...
}
like image 879
Matt3o12 Avatar asked Dec 14 '12 17:12

Matt3o12


People also ask

Can interface throw exception Java?

Yes, the abstract methods of an interface can throw an exception.

What is an interface exception handling in Java?

An interface method in Java can declare that a method throws a particular exception. This is a best practice (when not overused) since the interface defines what class of exception can be thrown. Checked exceptions by design require the caller to use try-catch or declare throws on the method.

Is interface an exception?

Java exceptions must all be descendants of the class Throwable. Since Throwable is a class and not an interface you cannot define an exception to be the implementation of an interface.

How do you catch an exception in Java?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.


1 Answers

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");
}
like image 106
Justin ᚅᚔᚈᚄᚒᚔ Avatar answered Sep 27 '22 16:09

Justin ᚅᚔᚈᚄᚒᚔ