title: PHP, How to catch a division by zero?
body: <p>I have a large mathematical expression that has to be created dynamically. For example, once I have parsed "something" the result will be a string like: <code>"$foo+$bar/$baz";</code>.</p>
  
  <p>So, for calculating the result of that expression I'm using the <code>eval</code> function... something like this:</p>
  
  <pre><code>eval("\$result = $expresion;");
  echo "The result is: $result";
  </code></pre>
  
  <p>The problem here is that sometimes I get errors that says there was a division by zero, and I don't know how to catch that Exception. I have tried things like:</p>
  
  <pre><code>eval("try{\$result = $expresion;}catch(Exception \$e){\$result = 0;}");
  echo "The result is: $result";
  </code></pre>
  
  <p>Or:</p>
  
  <pre><code>try{
      eval("\$result = $expresion;");
  }
  catch(Exception $e){
      $result = 0;
  }
  echo "The result is: $result";
  </code></pre>
  
  <p>But it does not work. So, how can I avoid that my application crashes when there is a division by zero?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>First, I want to clarify something: the expression is built dynamically, so I can't just eval if the denominator is zero. So... with regards to the Mark Baker's comment, let me give you an example. My parser could build something like this:</p>
  
  <pre><code>"$foo + $bar * ( $baz / ( $foz - $bak ) )"
  </code></pre>
  
  <p>The parser build the string step by step without worrying about the value of the vars... so in this case if <code>$foz == $bak</code> there's in fact a division by zero: <code>$baz / ( 0 )</code>.</p>
  
  <p>On the other hand as Pete suggested, I tried:</p>
  
  <pre><code>&lt;?php
  $a = 5;
  $b = 0;
  
  if(@eval(" try{ \$res = $a/$b; } catch(Exception \$e){}") === FALSE)
          $res = 0;
  echo "$res\n";
  ?&gt; 
  </code></pre>
  
  <p>But it does not print anything.</p>