5

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>';
MikeSchinkel
  • 245
  • 2
  • 10
Rarst
  • 153
  • 8
  • 4
    This reminds me of 1990s VB with On Error Resume Next. If something goes wrong don't ignore it. More serious errors await if ignored. – Jon Raynor Nov 17 '11 at 21:51
  • Rarst asked this question without showing code examples after an offline debate with me and then expanded into a general use-case discussion which will cause people to answer the general case and not focus on the specific case so I posted another question [about that specific use-case](http://programmers.stackexchange.com/questions/120391/is-error-suppression-a-valid-technique-for-testing-for-an-optional-array-key). – MikeSchinkel Nov 17 '11 at 22:46
  • @Rarst - The example you added was what triggered our debate but not what I would offer as a good example since we wouldn't want to emit `
  • `; a better example can be found [here](http://programmers.stackexchange.com/questions/120391/is-error-suppression-a-valid-technique-for-testing-for-an-optional-array-key). – MikeSchinkel Nov 17 '11 at 23:24
  • @Jon -- this was sort of acceptable in VB as it was the only way to trap exceptions. The "On Error Resume Next, do something that might fail, On Error GoTo 0, Check for failure" pattern is roughly equivalent to "Try ... Catch" in better languages. Except for being massively error prone! – James Anderson Nov 18 '11 at 04:21