php: Difference between Exception and RuntimeException?
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.
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
.