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...
}
Yes, the abstract methods of an interface can throw an exception.
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.
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.
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With