> 
________________________________
> From: Lamp Lists <lamp.li...@yahoo.com>
> To: php-general@lists.php.net
> Sent: Monday, April 13, 2009 9:29:16 AM
> Subject: [PHP] try - catch is not so clear to me...
> 
>  hi to all!
> 
> actually, the statement in the Subject line is not 100% correct. I understand 
> the purpose and how it works (at least I think I understand :-)) but to me 
> it's so complicated way?
> 
> let's take a look in example from php.net(http://us3.php.net/try)
> 
> 
> <?php
> function inverse($x) {
>     if (!$x) {
>         throw new Exception('Division by zero.');
>     }
>     else return 1/$x;
> }
> 
> try {
>     echo inverse(5) . "\n";
>     echo inverse(0) . "\n";
> } catch (Exception $e) {
>     echo 'Caught exception: ',  $e->getMessage(), "\n";
> }
> 
> // Continue execution
> echo 'Hello World';
> ?>  
> I would do the same thing, I think, less complicated:
> 
> <?php
> function inverse($x)
> {
>     if (!$x) {
>         echo 'Division by zero';
>     }
>     else return 1/$x;
> 
> }
> 
> echo inverse(5);
> echo inverse(0);
> 
> // Continue execution
> echo 'Hello world';
> ?>
> 
> I know this is "too simple, maybe not the best example", but can somebody 
> please explain "the purpose" of try/catch?
> 
> Thanks.
> 
> -LL


another example from php.net

<?php
try
{
  $connection = mysql_connect(...);
  if ($connection === false)
  {
    throw new Exception('Cannot connect do mysql');
  }

   /* ... do whatever you need with database, that may mail and throw 
exceptions too ... */

   mysql_close($connection);
}
catch (Exception $e)
{
   /* ... add logging stuff there if you need ... */

  echo "This page cannot be displayed";
}

?>
      

compare to:

<?php
  $connection = mysql_connect(...) or die('Cannot connect do mysql'. 
mysql_error());
?>
      


-LL


      

Reply via email to