Proper use of try .. catch

Should I use this error metadata method:

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?

quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in which case an array element exists.

+6
error-handling
source share
7 answers

The second example is bad. You take a lot of overhead to catch the exception when, as you demonstrate, it is just as easy to prevent the exception in the first place. In addition, you also assume that you know why this exception was thrown - if there were some other exception, for example, from memory or something else, you report it as a “field not found”, even if it is not So.

Keep in mind that try / catch in languages ​​like C ++ and Java are very expensive because of the state that they need to save and restore. Python, on the other hand, has very cheap exceptions, and they positively recommend that you use try / except for a simple check. But even in this case, catching everything and pretending that one kind of exception is still bad.

+10
source share
 //First let do the checks. if(!isset($this->dbfields[$var])) throw new FieldNotFoundException($var); //Now we're in the clear! return $this->dbfields[$var]; 
+4
source share

Capturing “Exceptions” does not mean that most of the time, considered good practice, of the two you showed, I would use option 1.

Catching all exceptions can hide another exception and hide it as a FileNotFoundException.

+3
source share

I prefer the former, but if dbfields [$ var] throws something sensible when you are accessing a nonexistent element, then I would prefer to just return it without checking.

I don’t particularly like changing the type of exception unless I have a good reason - also if you do, make sure you are trying to keep the original trace of the exception and stack.

+2
source share

Just re-read your explanations.

I assume that your method in # 1 will catch any exceptions that may be thrown and just return a bool. I definitely don't like catching the general exception most of the time, so No. 2 will not be my choice.

0
source share

"... or something else?"

Nothing is very good, so something else would be appropriate.

Correct version 2 to catch the correct exception, and not all possible exceptions. Publish this as option 3. I will outweigh something that catches a specific exception instead of an Exception .

0
source share

This is far from an agnostic language.

Some languages ​​will not cause errors to access non-existent fields, and the preferred template is highly dependent on the implementation of arrays, tables, objects, etc.

0
source share

All Articles