Php Exception Handling trycatchExceptions-PHP source code

Source: Internet
Author: User
Tags php exception handling
Ec (2); directory & nbsp; 1. & nbsp; what is an exception & nbsp; 2. d Entry & nbsp; 3. custom exception & nbsp; 4. & nbsp; multiple exceptions & nbsp; 5. throw an exception again & nbsp; 6. & nbsp; Program Stream exceptions & nbsp; 7. & nbsp; top-level exception handling program & nbsp script ec (2); script

Directory

1. What is an exception?
2. d getting started
3. custom exception
4. Multiple exceptions
5. Throw an exception again.
6. program flow exceptions
7. Top-level exception handling program
8. Error Code
9. Summary

What are exceptions.

With the advent of PHP 5, a new object-oriented model and a new error-oriented method for object processing are available. . Exceptions give us a big, better error, so that we can handle the behavior (exception) of custom script errors. Previously, PHP handled errors by making the error mark and trigger_error () function. These are good and good for the previous php5 days, but in the new object-oriented environment, we need more control.

We have a good clean code processing tutorial. In this tutorial, we will handle problems and how to handle them.
Get started with Getting started.

In the simplest form, exceptions are still very powerful, because they allow us to find the wrong location and time we want .. An exception in a more complex form gives us an alternative special error to return the signal function call used by the Code failed. We can use various functions to block the entire code. Let's dive and see what the fuss is. You can create an exception. php...

/**
*
* @ Check if number is greater than 3
*
* @ Param int
*
* @ Return bool on success
*
*/
Function checkNum ($ number ){
If ($ number> 3)
{
Throw new Exception ("Number is greater than 3 ");
}
Return true;
}

/*** Call the function ***/
CheckNum (28 );

?>

The above code will generate the following error:
Fatal error: Uncaught exception 'exception' with message 'Number is greater than 3' in/www/Exception. php: 15 Stack trace: #0/www/exception. php (21): checkNum (28) #1 {main} thrown in/www/exception. php on line 15 fatal error: the number of uncaptured exceptions and information exceeds 3 '/World Wide Web/exception. php: 15 stack trace: #0/World Wide Web/exception. php (21): checkNum (28) #1 (main) Throw/World Wide Web/online 15 exception. php

. This error occurs because an exception has been thrown in the checkNum function but has not been dropped to the network .. All exceptions must be caught or this error will occur .. One exception is the use of a catch Block. But first, the code we need to try causes an exception. So the order of things is: Therefore, the order of things is:

* Try
* Throw
* Catch

Remember, if you throw something, you must catch it. Code. It can be put into some effective code tests.

/**
*
* @ Check if number is greater than 3
*
* @ Param int
*
* @ Return bool on success
*
*/
Function checkNum ($ number ){
If ($ number> 3)
{
Throw new Exception ("Number is greater than 3 ");
}
Return true;
}

/*** Try block ***/
Try
{
CheckNum (28 );
/*** This code does not get excecuted if an exception is thrown ***/
Echo 'if you see this, the number is not greater than 3 ';
}
/*** Catch the exception here ***/
Catch (Exception $ e)
{
// Code to handle the Exception
Echo 'catch exception here
';
Echo 'message: '. $ e-> getMessage ().'
';
Echo 'more text or functions here .';
}
?>

When accessed, the above Code will be generated and output to the browser, similar to this:
Catch exception here Catch an exception
3 messages: messages larger than 3
. More text or functions here.

This allows you to execute code in one step and gain a grip on what is happening .. The function checkNum simply checks that a number is greater than 3. If not, exception and thrown error messages. Next, we have an attempt () block to call the checkNum () function. If the checkNum condition () function does not meet the conditions, exeption throws and is captured in the first catch Block .. You may have multiple catch blocks. PHP will try to parse any exceptions until the code block throws or ends. Any code after an exception is thrown is not executed. Any abnormal code in the future will not be executed.

In the catch () {} code first echo a line of text saying we have caught up with the exception, then the error message is contained In the exception class that calls the $ electronic "getMessage () method. . The error message is directly passed to the constructor exception class. When an exception is caught, we allocate it to an instance (object) of a variable or code. Now we have an exception object that contains our exception information. So, enough of the basics. Therefore, there is sufficient foundation. According to this document, we will explore more deeply...
M Exceptions Custom exception

. The most popular exception class courses can be extended to creating your own custom exception classes. When a new class is built based on PHP, it uses the parent company for unified construction and allows the inheritance of classAs. . Therefore, all methods can be used when the exception class is extended. You can run the filter_var () function on the basis of an invalid email address check.

Class customException extends Exception {

/**
*
* @ Return exception message
*
* @ Access public
*
* @ Return string
*
*/
Public function exceptionMessage (){
/*** The error message ***/
$ ErrorMsg = 'the email address'. $ this-> getMessage (). ', on line '.
$ This-> getLine (). 'in'. $ this-> getFile (). ', is invalid .';
/*** Return the error message ***/
Return $ errorMsg;
}

}/*** End of class ***/
?>

The class above is essentially an exception class on its own. It has the single addition of the exceptionMessage () method that callthe Exception class methods getLine () and getFile () and getMessage (). it has a single exceptionMessage except for the () method call exception handling class methods getLine () and GetFile () and getMessage (). As they are defined in the base class, the extended class * inherits * from it. Because they are defined in the base class, the extended class ** inherits from it. Lets take it for a test drive. allows you to test it.

/*** An invalid email address ***/
$ Email = "example @ phpro @ org ";
Try {
/*** Check the validity of the email address ***/
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
/*** If there is a problem, throw an exception ***/
Throw new customException ($ email );
}
}
Catch (customException $ e)
{
/*** Display the custom error message ***/
Echo"

". $ E-> errorMessage ()."

";
}

/*** The custome excetpion class ***/
Class customException extends Exception {
/**
*
* @ Return exception message
*
* @ Access public
*
* @ Return string
*
*/
Public function errorMessage (){
/*** The error message ***/
$ ErrorMsg = 'the email address'. $ this-> getMessage (). ', on line '.
$ This-> getLine (). 'in'. $ this-> getFile (). ', is invalid .';
/*** Return the error message ***/
Return $ errorMsg;
}

}/*** End of class ***/

?>

Obviously, the provided email address is invalid. When the filter_var () function returns Boolean false, an exception customException class is thrown. . If an exception is thrown, any normal exception is thrown. Even if only the parameter is passed to the customException class as the variable $ email, the parent class of all available methods can be abnormal, such as getMessage (), getLine (), and GetFile ().. Because PHP's object-oriented model includes a unified structure, when the variable $ email is passed to the customException class, it can be immediately provided to the parent class .. But this example shows only how to try, throw, and catch an exception .. In other cases, we need more. Multiple exceptions can be thrown and captured.
Multiple Exceptions

Multiple exceptions can take multiple forms. . They can be nested in multiple if/else blocks in one vswitch or. Yes, you can nest exceptions in multiple try {} catch () {} blocks. Yes, you can try to catch exception () blocks in multiple nests. A script may need to check for multiple conditions and different messages returned. A script may need to check multiple conditions and return different messages. Program flow may also need to change if an exception is thrown. The Program flow may also need to be changed if an exception is thrown. Lets see how we can nest an exception and check for different error conditions. Let's see how we can nested exceptions and different error condition checks. The customException class need not change for this. this does not need to be changed in The customException class. This is what is meant in PHP as re-usable code. This indicates reusable code in PHP. Here we see an example of using nested try {} catch () {} blocks. Here we see an attempt to use nesting, such as () catch.

Error_reporting (E_ALL );

$ Email = "example@phpro.org ";
Try {
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
Throw new customException ($ email );
}
Try {
If (strpos ($ email, 'phpro ')! = FALSE)
{
Throw new Exception ("$ email is funky ");
}
}
Catch (Exception $ e)
{
Echo'

'. $ E-> getMessage ().'

';
}
}
Catch (customException $ e)
{
Echo"

". $ E-> errorMessage ()."

";
}

Class customException extends Exception {

/**
*
* @ Return exception message
*
* @ Access public
*
* @ Return string
*
*/
Public function errorMessage (){
/*** The error message ***/
$ ErrorMsg = 'the email address'. $ this-> getMessage (). ', on line '.
$ This-> getLine (). 'in'. $ this-> getFile (). ', is invalid .';
/*** Return the error message ***/
Return $ errorMsg;
}

}/*** End of class ***/

?>

In the above example, the colors of the errors have been made red or blue to easily discern which error has been thrown. in the above example, the colors of these errors are red or blue, and it is not difficult to see that the errors have been thrown. The problem with this sort of code, or nested if/else blocks, is if the program CILS for large amounts of validation, we end up with very deeply nested code which can become very clumsy to read and debug. sort the Code with this, nested or problematic if/else block. if the program requires a lot of verification, we end up very deeply nested Code and may become very clumsy to read and debug. A better option is simply to code smarter. lets look at an option using only single if () blocks to check a condition. A better choice is code smarter. lets is in a single, if only the option () block check condition is used.

Error_reporting (E_ALL );

$ Email = "kevin@fish.phpro.org ";
Try {
/*** Check if email is valid ***/
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
Throw new customException ($ email );
}
/*** Check for fish ***/
If (strpos ($ email, 'fish ')! = FALSE)
{
Throw new Exception ("$ email is funky ");
}
/*** Check for example.org ***/
If ($ email! = 'Kevin @ example.org ');
{
Throw new customException ($ email );
}
}
Catch (customException $ e)
{
Echo'

'. $ E-> errorMessage ().'

';
}
Catch (Exception $ e)
{
Echo'

'. $ E-> getMessage ().'

';
}

Class customException extends Exception {

/**
*
* @ Return exception message
*
* @ Access public
*
* @ Return string
*
*/
Public function errorMessage (){
/*** The error message ***/
$ ErrorMsg = 'the email address'. $ this-> getMessage (). ', on line '.
$ This-> getLine (). 'in'. $ this-> getFile (). ', is invalid .';
/*** Return the error message ***/
Return $ errorMsg;
}

}/*** End of class ***/
?>

The encoding style above makes it easier to track and read a lot of consciousness. The two catch () blocks use the execution of this Code as exceptions and allow multiples. Again, it is the wrong color encoding. This time, we can see that PHP has successfully jumped to the correct capture () block to throw an error. In this case, the dollar email variable * fish *, so in its standard exception, and catch () block characters in the appropriate catch. The block is omitted. Only the base exception catch Block is used and the exception will be handled.
Re-throwing Exceptions Re-throw an exception

An exception can be thrown out again when you want to govern the program flow. if the condition does not meet and an exception is thrown, You can have different processing conditions based on the second condition, or you may wish to try to recover from the error. It is widely believed that the user's system errors are hidden from practice. Let's consider a simple database connection with the Professional Development Director. Because PDO is completely so amazing, it has a built-in exception. . If an error occurs, you must catch the database when attempting to connect to an exception. Although errors in the slave database may be meaningful to human-coded applications, it has very few or no relevant users .. Therefore, exceptions can be easily thrown by users by reusing beautiful and friendly information. For example, a failed Professional Development Director database error is as follows:
Unable to open database file
When a lower-level error is thrown again, an exception must be thrown in the lower-level. If the exception does not capture the package, the "bubble" stack will continue until a catch () block is found to process it. If no catch () block is found, the result of an uncaptured Exception error is returned. The following example demonstrates how to correctly rethrow an exception.

Try {
Try {
/*** Try to connect to a non-existant database ***/
$ Db = new PDO ("sqlite:/path/to/database. sdb ");
}
Catch (PDOException $ e)
{
/*** Rethrow the error to the custom handler ***/
Throw new customException ("Database unavailable ");
}
}
/*** Catch the customException here ***/
Catch (customException $ e)
{
/*** Echo the new error message ***/
Echo $ e-> errorMessage ();
}

Class customException extends Exception {

/**
*
* @ Return exception message
*
* @ Access public
*
* @ Return string
*
*/
Public function errorMessage (){
/*** The error message ***/
$ ErrorMsg ='

'. $ This-> getMessage ().'

';
/*** Return the error message ***/
Return $ errorMsg;
}

}/*** End of class ***/
?>

. From the code above, we can see a PDO exception when we try to connect to a non-existent database. . This exception is caught and re-handled with the customException class error, and gracefully exited the throw. Any un-. Any uncaptured exceptions should be considered as an application error.
Exceptions in the Program Flow with Exceptions Program Stream

Exceptions should not be used as vine, even if they seem to be the ideal choice for the ideal purpose try {} catch {} blocks. A good exception implemtation means that the Code will capture anything without trying () blocks .. The exception class should only be used for error conditions. The following is an incorrect example of abnormal use.

$ AnimalsArray = array ('dingo', 'wombat', 'Steve irwin', 'Kiwi ', 'hangaroo', 'platypus ');
Try {
/*** Loop over the array ***/
Foreach ($ animalsArray as $ value)
{
/*** If we find a kiwi ***/
If ($ value = 'Kiwi ')
{
/*** Throw an exception here ***/
Throw new Exception ("This is not an unsupported Alian Native ");
}
}
}
Catch (Exception $ e)
{
/*** Catch the exception here ***/
Echo $ e-> getMessage ();
}
?>

When the above script throws a value, an exception is found in the foreach loop. This is an exception class as a simple breakthrough here, abuse will make the same job clean. No error occurs, so no exception should be thrown.
Top Level Exception Handler Top-Level Exception handling program

The most striking feature of. PHP is the set_exception_handler () function. . This little magician takes care of the amount of exceptions thrown by the United Nations as the final opportunity to catch any previously uncaptured exceptions, that is, if no exceptions are caught in catch () blocks .. This function must be defined before being called back to exception_handler as its only parameter. The default_handler throws a parameter that is an exception object. . This lists the operations of the script.


/*** A default Exception handler ***/
Function my_default_handler ($ exception ){
Echo "Uncaught exception:", $ exception-> getMessage ();
}

/*** Set the default to handler to my_default_handler ***/
Set_exception_handler ('My _ default_handler ');

/*** Throw an exception ***/
Throw new Exception ('catch me if you can! ');

Echo 'this is not executed ';

?>

If you wanted to restore the default Exception handler, simple use the restore_exception_handler (); function. If you want to restore the default Exception handler, simply use the restore_exception_handler () function. This coshould also be used if your current default handler was another custom Exception class. This can also be used if your current default handler is another custom Exception class. The Exception classes are held in a stack can be restored with the restore_exception_handler () function as shown here. The Exception class is held in a stack and can be restored with restore_exception_handler () function, as shown below.

/*** An email to validate ***/
$ Email = 'Guru @ phpro.org ';

/*** Red error messages ***/
Function blue_default_handler ($ exception ){
Echo'

'. $ Exception-> getMessage ().'

';
}

/*** Blue error messages ***/
Function red_default_handler ($ exception ){
Echo'

'. $ Exception-> getMessage ().'

';
}

/*** Set the default to handler to red_default_handler ***/
Set_exception_handler ('red _ default_handler ');

/*** Some code here ***/
If (! Isset ($ email ))
{
/*** If there is no match ***/
Throw new exception ('no Email is set ');
}

/*** Set the default handler to blue_default_handler ***/
Set_exception_handler ('Blue _ default_handler ');

/*** Check the email value ***/
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
Throw new Exception ('invalidemail ');
}

/*** Restore the default handler ***/
Restore_exception_handler ();

If (strpos ($ email, 'guru ')! = False)
{
Throw new Exception ('Sorry, No gurus at phpro ');
}

Echo 'this is not executed ';

?>

So, from the script above we see the declaration of two Exception handlers, one makes the error messags red, and the other makes them blue. therefore, we can see two exception handling declaration scripts, one of which uses red and blue for messags. This is perhaps an abuse of the Exception functionality but serves well to demonstrate changes in classes as they occur. This may be an misuse of abnormal functions, but it can be well displayed in the classroom. The initial default handler is set to red. The initial default handler is set to red. The a check is run to see if an $ email variable is set. check whether The $ email variable is running. Try removing the $ email variable or commenting it out to see it work. Try to delete the email dollar variable or comment to see how it works. If the $ email varible is set, the code continues and the default handler is set to the blue_default_handler. If $ email varible is set, the code continues, and the default handler is blue_default_handler. Then using the filter_var () function, the $ email is tested for validity and if it fails, a blue message is shown. then, use the filter_var () function to test the validity of the email dollar. If it fails, a blue message is displayed. Try changing the value of the email to 1234 to see the results. Try to change the value of the email to 1234. Finally we see the use of restore_exception_handler (); which pops the stack and returns the default Exception handler to the red_default_handler. finally, we can see the pop-up stack of restore_exception_handler using (); and return the default exception handler red_default_handler. When any of these exceptions occur, code execution stops and control is passed to the handler. When these exceptions occur, the code execution stops and controls are passed to the handler. You notice at the bottom of the script above that the line You will notice at the bottom of the above script
Echo 'this is not executed'; echo 'this is not execute ';
Is never executed. It will never be executed. But... what if we wish to continue with the script and execute code below the thrown exceptions? What if we want to continue with the exception thrown by the script and execute the following code? This is the default behavior of Exceptions. This is the default act of Exceptions. Once outside the catch () {} block you are free to include whatever code you wish. Once captured outside () block, you can freely include any code desire.

Output buffering is Off by default in php. ini so it will need to be turned on via ob_start (). the output buffer is in php. the INI file is disabled by default, so it needs to be closed through ob_start (). We can begin output to the brower in the script and if an exception is thrown, still use header () to redirect based on the exception type. we can start to output the data to the script Brier. if an exception is thrown, the exception type of the header () redirection is still used.

Try {
/*** Try to connect to a non-existent database ***/
$ Dsn = new PDO ("sqlite:/path/to/database. php ");

/*** This code is never executed ***/
Echo 'move along, nothing to see here ';

}
Catch (PDOException $ e)
{
/*** Echo the error message ***/
Echo 'database Error: ', $ e-> getMessage (),'';
}

/*** More code and HTML here ***/
Echo'

Catch me if you can!

';

?>
Error Codes Error code

As seen in the beginning of this document, the Exception class contains a getCode () method that will fetch an error code, this can useful as you can define your own error codes as well as your own error messages. as we can see at the beginning of this article, the exception class contains a verification code () method that will get the error code, which can help you define your own error code and your own error information. This quick demonstration shows how. This shows how to quickly demonstrate.

/*** An invalid email address ***/
$ Email = 'example @ phpro @ org ';

Try {
/*** Validate the email address ***/
$ Db = validateEmail ($ email );
}
Catch (Exception $ e)
{
/*** Display the error code ***/
Echo 'error: '. $ e-> getCode ();
}

/**
*
* @ Validate an email
*
* @ Param string
*
* @ Throw standard exception on failure
*
*/
Function validateEmail ($ email ){
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
Throw new Exception ("Invalid Email", 10 );
}
}

?>

The above code returns the line:
Error: 10 Error: 10
Well, big deal you say... okay, big deal you say... OK, if we can define our own error codes, we can script based on thier value! Well, if we can define our own error codes and scripts, we can use them based on their values! The following script shows some of the possibilities. The following script shows some possibilities.

/*** An invalid email address ***/
$ Email = 'example @ phpro @ org ';

Try {
/*** Validate the email address ***/
$ Db = validateEmail ($ email );
}
Catch (Exception $ e)
{
/*** Display the error code ***/
Switch ($ e-> getCode ()){
Case 0:
Echo 'handle error here ';
Break;
Case 10:
Echo 'handle error condition here ';
Break;
Case 20:
Echo "handle other condition here ";
Break;
Default:
Echo 'some default handler here ';
}
}

/**
*
* @ Validate an email
*
* @ Param string
*
* @ Throw standard exception on failure
*
*/
Function validateEmail ($ email ){
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE)
{
Throw new Exception ("Invalid Email", 10 );
}
}

?>

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.