Back story: I have a class that handles a database query. The problem is that the query is only executed when needed, so this may sometimes be a bit far away from the place it’s created. Now if the wrapped SQL query fails, it becomes difficult to trace it back to it’s origin.
Now the idea is this: I’ll create a generic exception object (which gives me backtrace and everything) when creating that wrapper. When something happens during the actual execution, the pre-generated exception can be used to find the source of the problem when debugging.
This inevitably leads to the question: How expensive is it to generate an Exception object beforehand? Is it even a smart thing to do? How would you debug deferred SQL execution?
To clarify the process, here’s some pseudo code:
$list = new QueryWrapper("SELECT ...");
$list->setPage(5);
// Later...
foreach ($list as $entry) { ... }
Only when the foreach actually accesses $list is the query executed.
Update: Here’s a minimalistic implementation:
public function __construct($query, ... $params = array()) {
...
$this->createTrace = new \Exception();
}
// called by the Iterator's rewind()
private function runQuery() {
try {
// execute query;
}
catch(\Exception $e) {
throw new \Exception(
sprintf(
'Exception thrown after SQL error (created as %s)',
$this->createTrace->getTraceAsString()
),
0, $e
);
}
}
Instantiating an Exception which might be thrown later sounds like a rather unusual idea and is likely not what I would expect. I mean, the normal case would be to NOT throw an exception. So, most of the time you would create an Exception which is likely be never thrown/used.
An Exception which is thrown later in program flow will give you the stack trace anyway, so in my opinion: dont bother and dont do that.