PHP5 Program Exception Handling

Source: Internet
Author: User
Tags exception handling getmessage

How the exception works:
Try
{
Code processing program;
if (Error in code processing) throw new Exception (' Throw an exception ');/use throw keyword, followed by an object of Exception
//What you need to know is that PHP5 exceptions do not automatically throw exceptions
The following handler no longer executes after an exception is thrown
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 ()//is the same as Gettrace (), except that it is formatted as a string

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

Exception properties cannot be accessed directly in the calling code, but must be obtained by using the Fetch method, with only $message, $code can be set when a user throws an exception, which is done to the constructor of the exception class. The exception class can see that we can completely inherit the exception class to create our own exception class, not to throw the system default exception object when detecting errors, but to our custom exception class object, but we can only inherit constructors, ToString () The properties of the method and exception.

Class MyExceptionextEnds Exception
{
function __tostring ()
{
Return ' <div class= ' ERROR >Exception'. $this->GetCode ().':'. $this->getMessage ().' in'. $this->GetFile ().' on line'. $this->getline (). '</div> Overwrite throws exception result
}
}

Call our custom exception class in code
Try
{
throw new MyException (' Error ', 10);//For simplicity, throw the custom exception object directly
}
catch (MyException $e)
{
echo $e//Because our custom exception has changed the way it is exported, you can simply enter the exception object here, because it is called __tostring () once the Echo or print directly outputs the exception instance.
}

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

Constructors
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 invoke database connection after passing in parameters
$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, username or password error";
throw new MyException ($exceptionstring, 0);//Throw Custom Exception object, instance object with parameter error
}
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: <font color=red> $thedb </font> does not exist";
throw new MyException ($exceptionstring, 1);
}
catch (MyException $e) {
Echo $e;
}
}

Execute a Update,delete
Public function Execute ($thequery) {
try {
if ([email=! @mysql_query]! @mysql_query[/email] ($thequery, $this->db)) {
$exceptionstring = "Wrong sqlStatement: <font color=red> $thequery </font> ";
throw new MyException ($exceptionstring, 2);
} else {
echo "Update/delete affected:". Mysql_affected_rows (). "Line <br/>";
}
catch (MyException $e) {
Echo $e;
}
}

return SUSSU Results
Public Function GetRows ($thequery) {
try {
if (! $aquery =@ mysql_query ($thequery)) {
$exceptionstring = "Incorrect query statement: <font color=red> $thequery </font>";
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 = "Close Connection Failed";
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]. " <br/> ";
}
?>

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.