What is the exact semantic difference between \Exception
and \RuntimeException
in PHP? When we should use the former and when the latter?
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.