Re: Exception

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Dec 04, 2005 at 08:07:48PM +0330, mr php wrote:
> Hello
> Is it good to use exception handling for error handling or I should use only
> for exceptions?
> For example:
> Is it good to throwing user input errors with throw new Exception().

I'm not sure if I understand how you mean by this but it sounds to
me that your asking if you should use exception catching vs if
statments:

try {
  is_valid_username($username);
catch (Exception $e) {
  $errors[] = $e->errorMessage;
}

imo, programming like that doesn't make sense, exceptions are more
designed for errors in assumed succesfull code. Consider:

<?php

try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', '', '');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "select bar from foo";
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

}
catch (PDOException $e) {
    echo $e, "\n";
    exit();
}

// some code to use the valid $stmt object
?>

There are two places where that code will issue an exception:
  1. if a connection to the db fails, which it shouldn't
  2. if the column bar doesn't exit of table foo doesn't exist
     which should exist (unless the DBA decides to rename the table
     or column.

After the catch statement, I know that $stmt is going to be valid
and can check for valid results or not.

The use of the try catch is to ensure that something that is
suppose to happen 100% of the time succesfully, if it doesn't we
have an exceptional case and should bail out in a friendly
manner.

Curt.
-- 
cat .signature: No such file or directory

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux