{PHP 5 exception (exception )}

Source: Internet
Author: User

Exception ):Exception Handling is used to change the normal process of the script when a specified error (exception) occurs.

When an exception is triggered, it usually occurs:

  • The current Code status is saved.
  • Code execution is switched to a predefined exception processor Function
  • Depending on the situation, the processor may re-execute the code from the saved code status, terminate the script execution, or continue to execute the script from another position in the code

We will display different error handling methods:

  • Basic usage of exceptions
  • Create a custom exception Processor
  • Multiple exceptions
  • Throw an exception again.
  • Set the top-level exception Processor
Basic usage: Try, throw, and catch
To avoid errors in the above example, we need to create appropriate code to handle exceptions.
The processing process should include:
Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the Code continues as usual. If an exception is triggered, an exception is thrown. Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The catch-"catch" code block captures exceptions and creates an object containing exception information.

<? 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 ';
?>

~ Create a custom exception class

It is very easy to create a custom exception handler. We have simply created a special class. When an exception occurs in PHP, we can call its function. This class must be an extension of the exception class.

This custom exception class inherits all attributes of the PHP exception class. You can add custom functions to it.

Let's start to create the exception class:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example...com";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
}

catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>

~ Multiple exceptions

Multiple exceptions can be used for a script to detect multiple cases.

You can use multiple if. Else code blocks, a switch code block, or nested exceptions. These exceptions can use different exception classes and return different error messages:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}

catch (customException $e)
{
echo $e->errorMessage();
}

catch(Exception $e)
{
echo $e->getMessage();
}
?>

~ Throw an exception again.

Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" code block.

The script should hide system errors from users. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can throw an exception with user-friendly messages again:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}

$email = "someone@example.com";

try
{
try
{
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e)
{
//re-throw exception
throw new customException($email);
}
}

catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>

~ Top level exception handler)

The set_exception_handler () function can be used to process all user-defined functions without capturing exceptions.

<?phpfunction myException($exception){echo "<b>Exception:</b> " , $exception->getMessage();}set_exception_handler('myException');throw new Exception('Uncaught Exception occurred');?>

The output of the above Code should be similar to the following:

Exception: Uncaught Exception occurred

In the above Code, the "catch" code block does not exist, but triggers the exception handler at the top layer. This function should be used to capture all exceptions that are not captured.

Abnormal rules
  • Code that requires exception handling should be placed in the try code block to capture potential exceptions.
  • Each try or throw code block must have at least one catch code block.
  • Multiple catch code blocks can capture different types of exceptions.
  • You can throw a (re-thrown) exception again in the catch code block in the try code block.

In short: if an exception is thrown, it must be caught.

~

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.