Is error suppression acceptable in role of logic mechanism?

Posted by Rarst on Programmers See other posts from Programmers or by Rarst
Published on 2011-11-17T21:02:35Z Indexed on 2011/11/18 2:02 UTC
Read the original article Hit count: 213

Filed under:

This came up in code review at work in context of PHP and @ operator. However I want to try keep this in more generic form, since few question about it I found on SO got bogged down in technical specifics.

Accessing array field, which is not set, results in error message and is commonly handled by following logic (pseudo code):

if field value is set
   output field value

Code in question was doing it like:

start ignoring errors
output field value
stop ignoring errors

The reasoning for latter was that it's more compact and readable code in this specific case. I feel that those benefits do not justify misuse (IMO) of language mechanics.

  • Is such code is being "clever" in a bad way?

  • Is discarding possible error (for any reason) acceptable practice over explicitly handling it (even if that leads to more extensive and/or intensive code)?

  • Is it acceptable for programming operators to cross boundaries of intended use (like in this case using error handling for controlling output)?

Edit

I wanted to keep it more generic, but specific code being discussed was like this:

if ( isset($array['field']) ) {
    echo '<li>' . $array['field'] . '</li>';
}

vs the following example:

echo '<li>' . @$array['field'] . '</li>';

© Programmers or respective owner

Related posts about error-handling