PHP5 program exception Handling _php Tutorial

Source: Internet
Author: User
How the exception works:
Try
{
Code processing program;
if (Code handling error) throw new Exception (' throws an exception ');//Use the Throw keyword, followed by an object of Exception
It is necessary to note that the PHP5 exception does not automatically throw an exception
After throwing an exception, the following handler no longer executes
Code processing program;
}
Catch Exception $e
{
Handling exceptions;
such as: Echo ' Exception '. $e->getcode (). ': '. $e->getmessage (). ' In '. $e->getfile (). ' On line '. $e->getline ();
}

See how the thrown exception class system is defined
Class Exception
{
protected $message = ' Unknown exception ';
protected $code = 0;
protected $file;
protected $line;

function __construct ($message =null, $code =0);

Final function getMessage ();
Final function GetCode ();
Final function getFile ();
Final function getLine ();
Final function gettrace ();
Final function gettraceasstring ();//As with Gettrace (), except that it will be formatted as a string

function __tostring ()//The method is called automatically when a string representation of an object is required, that is, once echo or print outputs the exception instance directly, it is called
}

The exception property cannot be accessed directly in the calling code, but must use the Get method to obtain its property value, only with $message, $code can be set when the user throws an exception, that is, the constructor for the exception class is completed. It can be seen from the exception class that we can inherit the exception class to create our own exception class, and we will not throw the system default exception object when detecting an error, but rather our own custom exception class object, but we can only inherit the constructor, ToString () The properties of the method and exception.

Class MyException extEnds Exception
{
function __tostring ()
{
Return ' Exception '. $this->getcode (). ': '. $this->getmessage (). ' In '. $this->getfile (). ' On line '. $this->getline (). '; /Overwrite throws exception result
}
}

Calling our custom exception class in code
Try
{
throw new MyException (' Error ', 10);//For simplicity, throw a custom exception object directly
}
catch (MyException $e)
{
echo $e;//Because our custom exception has changed the output mode, so here directly enter the exception object, because once echo or print directly output exception instance will be called __tostring ()
}

The above single-room introduction of the exception, below we introduce the exception to our DatabaseProcessing class to see how to use the
Class MyException extends exception{
function __construct ($message =null, $code =0)
{
Parent::__construct ($message, $code);
}
function __tostring ()
{
Return ' Exception '. $this->getcode (). ': '. $this->getmessage (). ' In File: '. $this->getfile (). ' On line: '. $this->getline (). '; /Overwrite throws exception result
}
}
Class MyDB {
private $user;//user name
private $pass;//password
private $host;//database IP address or localhost
Private $db; Database name

constructor function
Public Function __construct () {
$num _args = Func_num_args ();

if ($num _args > 0) {
$args = Func_get_args ();
$this->host = $args [0];
$this->user = $args [1];
$this->pass = $args [2];
Automatically call database connections after parameters are passed in
$this->connect ();
}
}

Database connection
Private Function Connect () {
Exception handling
try {
if (! $this->db =@ MySQL_connect ($this->host, $this->user, $this->pass)) {
$exceptionstring = "Connection failed: Host, user name or password error";
throw new MyException ($exceptionstring, 0);//Throw a custom exception object with an argument error when the instance object
}
} catch (MyException $e) {
Echo $e;
}
}

Database selection
Public Function Selectdb ($thedb) {
try {
if ([email=! @mysql_select_db]! @mysql_select_db [/email] ($thedb, $this->db)) {
$exceptionstring = "Database: $thedb does not exist";
throw new MyException ($exceptionstring, 1);
}
} catch (MyException $e) {
Echo $e;
}
}

Perform a update,delete
Public function Execute ($thequery) {
try {
if ([email=! @mysql_query]! @mysql_query [/email] ($thequery, $this->db)) {
$exceptionstring = "Error in SQL Statement: $thequery ";
throw new MyException ($exceptionstring, 2);
} else {
echo "Update/delete affected:". Mysql_affected_rows (). "Line
";
}
} catch (MyException $e) {
Echo $e;
}
}

Return socialize Results
Public Function GetRows ($thequery) {
try {
if (! $aquery =@ mysql_query ($thequery)) {
$exceptionstring = "Error query statement: $thequery";
throw new MyException ($exceptionstring, 3);
} else {
while ($adata = Mysql_fetch_array ($aquery)) {
$returnarr [] = $adata;
}
return $returnarr;
}
} catch (MyException $e) {
Echo $e;
}
}

destructor Close Connection
Public Function __destruct () {
try {
if ([email=! @mysql_close]! @mysql_close [/email] ($this->db)) {
$exceptionstring = "Failed to close connection";
throw new MyException ($exceptionstring, 4);
}
} catch (MyException $e) {
Echo $e;
}
}

}
Instance class
$mydb = new MyDB ("localhost", "root", "123456");
Select Database
$mydb->selectdb ("Tonlong");
Perform an update operation
$adata = $mydb->execute ("Update db_news set hits=hits+1 where id=3");
Query output
$data = $mydb->getrows ("Select title from Db_news");
for ($i = 0; $i < count ($data); $i + +) {
echo $data [$i][0]. "
";
}
?>

http://www.bkjia.com/PHPjc/629750.html www.bkjia.com true http://www.bkjia.com/PHPjc/629750.html techarticle How the exception works: try {code handler; if (Code handling error) throw new Exception (' Throw an exception ');//Use the Throw keyword, followed by an object of Exception//...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.