Should I be using this method of throwing errors:
if (isset($this->dbfields[$var])) { return $this->dbfields[$var]; } else { throw new FieldNotFoundException($var); }
or this style:
try { return $this->dbfields[$var]; } catch (Exception $e) { throw new FieldNotFoundException($var); }
…or something else altogether?
quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in this case, whether the array element exists.
The second example is bad. You’re taking a lot of overhead to catch an exception when, as you demonstrate, it’s just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown – if there was some other exception, like say an out of memory or something, you’re reporting it as a ‘field not found’ even if it wasn’t.
Keep in mind that
try/catchin languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use atry/exceptfor simple validation. But even so, catching everything and pretending it’s one type of exception is still bad.