When would an exception be constructed and not thrown?
If you are extending exceptions in some way (adding new functionality, for instance), then, testing that new functionality will involve instantiating the new extended exceptions without throwing them; the capability of being thrown doesn't need to be tested because it is implicit of any subclass of Exception.
At first sight of your question, I thought I'd be able to produce many acceptable answers. As it happens, I can only provide that one. This suggests that your question is good, but, because there is at least one, I don't consider it completely useless to know that the stack trace is populated at instantiation time. Maybe others can suggest more significance to the distinction between exception instantiation and throwing.
It is interesting though, the difficulty in answering that question tempts the possibility that a throw is merely a subtype of a normal return; anything that could be returned, could be thrown also:
Code: Select all
function throwingExplode($separator, $str) {
$e = new Exception;
$e->explosion = explode($separator, $str);
throw $e; }
try { throwingExplode('/', 'foo/bar/zim'); } catch (Exception $e) { var_dump($e->explosion); }
PHP complicates things by requiring the-datum-being-thrown to be an instance of Exception. If that requirement wasn't present that last snippet might look like this:
Code: Select all
function throwingExplode($separator, $str) { throw explode($separator, $str); }
try { throwingExplode('/', 'foo/bar/zim'); } catch ($explosion) { var_dump($explosion); }
...which supports my assertion more obviously.
If this is the case, it might explain why it is so rarely required to merely return an exception. A throw will essentially do the same thing i.e. gets the Exception to you from inside whatever creates it.