Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LogicException vs. RuntimeException

I was wondering if there was a rule saying when to use which Exception in PHP... When do I have to throw a LogicException and when a RuntimeException?

For example when it comes to exceptions like PageNotFoundException, from which exception class should I inherit?

like image 447
Nedec Avatar asked Apr 07 '11 19:04

Nedec


People also ask

When to use Runtime exception PHP?

RuntimeException is thrown if an error which can only be found on runtime occurs. It means that whenever You are expecting something that normally should work, to go wrong eg: division by zero or array index out of range etc. You can throw RuntimeException.

What is difference between exception and runtime exception?

The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked.

How can I catch exception in PHP?

Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }


1 Answers

LogicException seems like it's for "this can never happen" bug checks:

Exception that represents error in the program logic. This kind of exception should directly lead to a fix in your code.

A few of the other SPL exceptions, like BadFunctionCallException inherit from it.

RuntimeException is for cases where an error happens that could only be detected while the program is running. The naming is a holdover from compiled languages, where certain errors can be detected at compile time. Like LogicException, a few of the other SPL exceptions inherit from it.

You probably don't want to use either of these as the base for your own specific extensions unless you know for sure that your code could produce another exception in the inheritance hierarchy and you'd want to catch any of those instead of your specific exception or all exceptions.

like image 70
Charles Avatar answered Sep 18 '22 12:09

Charles