Php: Difference between Exception and RuntimeException?

What is the exact semantic difference between \Exception and \RuntimeException in php?
When will we use the first and when is the last?

+6
source share
2 answers

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

RuntimeException is thrown if an error that can only be found at runtime.

This means that whenever you expect something that normally should work, make a mistake, for example: division by zero or array index out of range, etc. You can throw a RuntimeException.

As for Exception , this is a very general exception, and I would call it "last resort." You can add it as the last in "try" to make sure that you handle all exceptions.

Example:

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

Hope this is clear now.

+8
source

The only difference between the two is semantic. RuntimeException inherits from Exception . There are basically no other differences.

You can create your own exceptions that inherit from both of the above, but the most commonly used is inheritance from Exception .

+2
source

Source: https://habr.com/ru/post/1014004/


All Articles