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.
Generally, you should only use a try-catch if there is something that you can do in the catch. Can you retry the failed connection or otherwise help the user to continue? Do you want to log the exception? If there's nothing you can do to recover or gracefully degrade, there is no point in catching the exception.
Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.
No, you should not wrap all of your code in a try-catch.
A try / catch block is basically used to handle errors in JavaScript. You use this when you don't want an error in your script to break your code.
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
/catch
in 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 a try
/except
for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.
//First let's do the checks.
if(!isset($this->dbfields[$var]))
throw new FieldNotFoundException($var);
//Now we're in the clear!
return $this->dbfields[$var];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With