Question

A long time ago I used to use "or die" in my PHP code. Especially like this:

$q = mysql_query('......') or die(mysql_error());

Obviously, that's pretty shameful these days, but the X or Y principle still speaks to me. So I though I'd try this:

$r = $this->exec($query) or throw new Exception('FAIL');

but that results in a parse error! What's the best practice for such statements. It has to look nice as well (obviously!)...

I don't like

if ( !($r = $this->exec($query)) ) throw new ...

or

$r = $this->exec($query)
if ( !$r ) throw new ....

Any favourites? Discouragements? Best practices? Speed is always nice.

Was it helpful?

Solution

There's nothing wrong with the two examples you used, except that you've sandwitched them onto one line.

I'm not sure what you're looking for, or why you're finding fault with an if statement - it's pretty tried and true at this point. That said, you can do something like this to shoe-horn in the or operator, but whoever maintains your code after you're gone will curse you.

function throw_ex($what) {
  throw $what;
}

function fails() {
  return false;
}

$x = fails() or throw_ex(new exception("failed"));

I don't see how this gains you anything over the ol' if statement.

OTHER TIPS

Fact of the matter is, you should be using if statements to catch actual, recoverable errors. Especially if you are using InnoDB which can sometimes have deadlocks during normal operation and the proper way to handle them isn't to die(), but simply submit the query again.

More info here: http://arjen-lentz.livejournal.com/150464.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top