PHP: catch exception in cascade. Is it possible?
I really need your help...
How can I catch exception in cascade? I have a function ( A ) that call another function in another file ( B ) that call another function in another file ( C ). How can I get in the catch of the function A, the errors of the function C? Is it possible? Look my example below... I tried to be the most clear possible...
// This code is in a file ( file A ) that call a function of a file B
require_once('/User_Login.php');
try
{
CREATE_NEW_User_Login(arr_Test, 'hello');
return true;
}
catch(Exception $e)
{
echo $e->getMessage();
return false;
}
}
// This code is in another file ( file B ) that call a function of a file C
public function CREATE_NEW_User_Login($_INPUT_Array = null, $_INPUT__Password = null)
{
// Db connection...
require_once('/User__DBclass.php');
$DBCl_User = new User($DBConn, null);
$DBCl_User->SET__CLASS_ATTRIBUTES_Value__by_Array($_INPUT_Array);
$DBCl_User->SETTER__user_pass(md5($_INPUT__Password));
$this->config['mysqli']->beginTransaction();
try
{
$DBCl_User->INSERT__NEW_ROW())
return true;
}
catch(Exception $e)
{
echo $e->getMessage();
return false;
}
}
// This code is in another file ( file C )
// In the User Class ( file: User__DBclass.开发者_如何学Cphp )
public function INSERT__NEW_ROW()
{
$this->config['stmt'] = $this->config['mysqli']->prepare('INSERT INTO tbl_user
SET user_id = :user_id,
user_name = :user_name,
act_code = :act_code;');
$this->config['stmt']->bindParam(':user_id', $this->user_id, PDO::PARAM_INT);
$this->config['stmt']->bindParam(':user_name', $this->user_name, PDO::PARAM_STR);
$this->config['stmt']->bindParam(':act_code', $this->act_code, PDO::PARAM_STR);
try
{
$this->config['stmt']->execute();
$this->user_id = intval($this->config['mysqli']->lastInsertId());
return $this->user_id;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
If you want to cascade the exceptions, then you need to throw them again instead of just returning false.
You can either create a new exception type for each of your exception, or your can create a general exception and set the appropriate message and code.
catch(Exception $e)
{
//do something here if you want
throw $e;
}
Reference : http://php.net/manual/en/language.exceptions.php
Just don't catch the exception in the function where it is thrown. Then it'll be caught in your calling function.
This is the basic comportment of Exception : if you don't catch directly an exception this one is thrown to the upper element and so on to the "Root script".
Attention, you must catch the Exception, otherwise you'll get an error.
You can also "re"throwing an Exception from a catch block, like this:
catch(PDOException $e) {
throw $e;
}
精彩评论