Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: Difference between Exception and RuntimeException?

What is the exact semantic difference between \Exception and \RuntimeException in PHP? When we should use the former and when the latter?

like image 279
sensorario Avatar asked Jan 12 '17 08:01

sensorario


2 Answers

Exception is a base class of all exceptions in PHP (including RuntimeException). As the documentation says:

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.

As for Exception, it is a very generic exception and I would call it a "last resort". You can add it as a last one in "try" just to be sure You are handling all exceptions.

Example:

try {
    //code...
} catch(RuntimeException $e) {
    echo ("RuntimeException..."); 
} catch(Exception $e) {
    echo ("Error something went wrong!"); 
    var_dump($e); 
}

Hope it is a clear now.

like image 64
malutki5200 Avatar answered Oct 08 '22 13:10

malutki5200


The only difference between those two is semantic. The \RuntimeException inherits from \Exception. Basically there are no other differences.

You can create your own exceptions inheriting from both of above, the most common usage is to inheritit from \Exception.

like image 4
Mateusz Woźniak Avatar answered Oct 08 '22 13:10

Mateusz Woźniak