PHP exception handling Try Catch exceptions

Source: Internet
Author: User
Tags foreach error code exception handling getmessage php exception handling sqlite stack trace try catch

Directory

1. What is an exception
2. D Introduction
3. Custom Exceptions
4. Multiple exceptions
5. Throw the exception again
6. Exception to program flow
7. Top level Exception Handler
8. Error code
9. The SUMMARY

What is the exception.

With the advent of PHP 5, there is a new object-oriented model and a new object handling error-oriented approach. The exception gives us a great deal of a better error to let us customize the behavior (exception) encountered when the script is wrong. Previous PHP processing functions were made by making errors from error flags and TRIGGER_ERROR () functions. These are good, good days before the php5, but in the new object-oriented environment, we need greater control.

We have a good clean code-handling tutorial. In this tutorial, we will address the issues and how to deal with them.
Getting Started. Entry.

. In the simplest form, the exception is still very strong, because they enable us to find the wrong place and the time we want. In a more complex form the exception gives us an alternative to the special error The return code uses a signal function call that failed. We can use the various features of the code to block them all. Can let dive and see what a fuss. Lets you create a name called exception.php ...

<?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 produce this error:
Fatal error:uncaught Exception ' exception ' with message ' # is greater than 3 ' in/www/exception.php:15 Stack trace: #0/www/exception.php: Checknum #1 {main} thrown in/www/exception.php on line 15 fatal error: Exception exception not caught with information ' number ' greater than 3 '/World Wide Web/EXC Eption.php:15 stack trace: #0/World Wide Web/exception.php: Checknum (28) # # (main) throw/World Wide Web/online exception.php

This error is due to an exception that has been thrown in the Checknum function, but has not been caught. All exceptions must be captured or this error will occur ... one exception is found to use a catch block. But first we need to try the code to throw an exception. So the order of things is: Therefore, the sequence of things is:

* Try Attempt
* Throw Cast
* Catch capture

. Remember, if you throw something, you have to catch it. Code. Allows you to put it into a number of valid coding tests.

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

/*** Try block ***/
Try
{
Checknum (28);
/*** This code does not get excecuted if a exception is thrown ***/
Echo ' If you are not greater than 3 ';
}
/*** Catch the exception here ***/
catch (Exception $e)
{
Code to handle the Exception
Echo ' Catch exception here<br/> ';
echo ' message: '. $e-> getMessage (). ' <br/> ';
Echo ' more text or functions here. '
}
?>

When accessed, the above code will produce output to the browser similar to this:
Catch exception here to catch an exception
3 message: number is greater than 3
. More text or functions here.

It allows you to step through the code and get a grip on what's going on. function Checknum simply check that a number is greater than 3. If not, the exception is thrown with the error message. Second, we have a try () block to make the call to the Checknum () function. If the checknum condition () function is not satisfied, the exeption is thrown and will be caught in the first catch block ... you may have more than one catch block. PHP will attempt to parse any exceptions until this block of code is thrown or the code block ends. Any code after a exception is thrown isn't executed. Any subsequent exception codes will not be executed.

In the first echoing line of the catch () {} code saying we've caught the exception, the error message is contained in the exception class that calls the $ e-getMessage () method.. Error messages are passed directly to the constructed exception class. When catching the thrown exception, we assign it to an instance (object) of a variable or use in code, and now we have an exception object that contains our exception information. So, enough of the basics. Therefore, sufficient basis. We follow this document and we will explore deeper ...
Custom Exceptions Customization exception

An exception class favorite course can be extended to create your own custom exception class. When a new class is based on PHP using the parent company to unify the construction and allow the inheritance of classas. Therefore, when an exception class is extended, all methods can be used. Can be taken to take a class using an invalid email address check based on the value returned by the Filter_var () function to run it.

<?php
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 of the error message ***/
return $ERRORMSG;
}

}/*** end of class ***/
?>

The class above is essentially a exception class on its own. The classes above are essentially their own exception classes. It has the single addition of the Exceptionmessage () method, that calls Exception class methods () and Getline () and GetMessage (). It has a single exceptionmessage except () method call exception Handling class method Getline () and GetFile () and GetMessage (). As they are defined in the base class, the extended class is *inherits* from it. Because they are defined in the base class, the extended class * * inherits from it. Lets take it for a test drive. Can let take a test drive it.

<?php

/*** An invalid e-mail address ***/
$email = "example@phpro@org";
try    {
/*** check the VA Lidity of the email address ***/
if (Filter_var ($email, filter_validate_email) = FALSE)
{
/*** if there is a problem, throw a exception ***/
throw new Customexception ($email);

}
catch (Customexception $e)
{
/*** display the custom error message ***/
echo <p style= ' color: Red ' > '. $e-> errormessage (). "</p>";
}

/*** 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 of the error message ***/
return $ERRORMSG;
}

}/*** end of class ***/

?>

Obviously, the provided email address is invalid when the Filter_var () function returns a Boolean false throw an exception to the Customexception class. Throws an exception to any normal exception. Even if only parameters are passed to the Customexception class is a variable $ email, all available method parent classes can be abnormal, such as getmessage (), Getline (), and GetFile (). Because the object-oriented model of PHP includes a unified construct, when the variable $ E-mail is delivered to the Customexception class, which can be provided immediately to the parent class. But this example shows only how to try, throw, and catch an exception. There are times when we need more than that. Multiple exceptions can be thrown and captured.
Multiple Exceptions multiple exceptions

Multiple exceptions can take many forms ... they can be in a lot of if/else blocks, in a switch or nesting. Yes, can nest exceptions in multiple try{} catch () {} blocks. Yep, you can try to catch an exception () () () block in multiple nests. A script might need to check for multiple conditions and different messages returned. The scripts may need to check multiple conditions and different message returns. Program flow might also need to change if a exception is thrown. The process may also need to be changed if an exception is thrown. Lets see us can nest an exception with check for different error conditions. Let's look at how we can nest exceptions and different error condition checks. The Customexception class need not changes to this. In the Customexception class there is no need to change that. This is meant in PHP as re-usable code. That's what it means to be reusable in PHP. Here we can see a example of using nested try{} catch () {} blocks. Here we have an attempt to use nesting, such as () catch () () block.

<?php
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 ' <p style= ' color:blue ' > '. $e-> getMessage (). ' </p> ';
}
}
catch (Customexception $e)
{
echo "<p style= ' color:red ' >". $e-> errormessage (). "</p>";
}

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 of the error message ***/
return $ERRORMSG;
}

}/*** end of class ***/

?>

In the above example, the colors's errors have been made red or blue to easily discern which error has been. On In the example of the face, these wrong colors are made in 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, are if the program calls for large amounts of validation, we End/Very deeply nested code which can become very clumsy to read and debug. Sorting with this code, nesting or problem of the If/else block, if the program is going to require a lot of validation, we Ultimately very deep nesting code that can become very clumsy to read and debug. A better option is simply to code smarter. Lets look in an option use only one if () blocks to check a condition. A better option is to code smarter.lets in a single, if only () block check condition option.

<?php
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 ' <p style= ' color:red ' > '. $e-> errormessage (). ' </p> ';
}
catch (Exception $e)
{
Echo ' <p style= ' color:blue ' > '. $e-> getMessage (). ' </p> ';
}

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 of the error message ***/
return $ERRORMSG;
}

}/*** end of class ***/
?>

. The above coding style makes a lot of sense and easier to track and read. The execution of this code is used as an exception in the two catch () block to allow multiple. Again is the wrong color coding, this time we see that PHP has successfully jumped to the correct catch () block corresponding to the throw error. In this case, the dollar's email variable's * fish *, so in its standard exception, and in the appropriate Catch Capture () () block word. Blocks are omitted, only the base exception catch block is used, which will handle exceptions there.
re-throwing exceptions throw the exception again

An exception can be thrown back when you want to govern the flow of the program. If the condition is not met and throws an exception, you can have different processing based on the second condition, or you may wish to try to recover from the error. It is generally accepted that the user's system error is hidden from practice. Let's consider a simple database connection with a professional development director. Because PDO is completely so amazing, it has a built-in exception. If an error occurs, when an attempt is made to connect to an exception, the database must be caught. While errors from a database may be meaningful to the person coding the application, it has little or no relevant users. Therefore, exceptions can be used to reuse beautiful and friendly information that users are more likely to understand to throw. For example: A failed Professional Development Director database error is this:
Unable to open database file
The exception must be thrown in with an internal one when the error is thrown again. If the exception does not catch the wrapper, the "bubble" stack continues until a catch () () block is found to handle it. The result of an unexpected error that was not caught if the () () block was found. The following example shows how to correctly throw an exception back.

<?php
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 = ' <p style= ' color:red; > '. $this-> getMessage (). ' </p> ';
/*** Return of the error message ***/
return $ERRORMSG;
}

}/*** end of class ***/
?>

. From the above code, we see a PDO exception when we try to connect to a nonexistent database. The exception is to catch and reconnect with the Customexception class and gracefully exit the throw. Any un-. An exception that is not caught should be treated as an application error.
Program flows with exceptions exception

Exceptions should not be used as vines, even though they seem ideal for ideal selection of try{} catch{} blocks. A good exception implemtation means that the code will catch anything without an attempt () () block. The exception class should be used only for error conditions. The following is an example of an incorrect use of exceptions.

<?php

$animalsArray = Array (' Dingo ', ' wombat ', ' Steve Irwin ', ' kiwi ', ' kangaroo ', ' platypus ');
try {
/*** loop over the array ***/
foreach ($animalsArray as $value)
{
/*** if we find a Kiwi ***/
if ($value = ' Kiwi ')
{
/*** throw a exception here ***/
throw new Exception ("This isn't an Australian Native");
}
}
}
catch (Exception $e)
{
/*** Catch the exception here ***/
echo $e-> getMessage ();
}
?>

. When the above script throws a value, the exception is found in the Foreach loop. This is an exception class as a simple breakthrough here after abusing will do the same job clean. No errors occur, so there should be no exceptions thrown.
Top level Exception Handler top-level exception handler

The most striking feature of PHP is the Set_exception_handler () function. This little magician, taking care of the United Nations into the amount of the exception the last chance to catch any previously not caught exception, namely: if there is no exception in the catch () () block capture ... This function must be defined for any requirements before it is invoked as its only parameter callback Exception_handler. The Default_handler has thrown a parameter that is an exception object ... this lists the operations of the script.


<?php

/*** 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 ' is not executed ';

?>

If you are wanted to restore the default Exception handler, simple use the Restore_exception_handler (); Functions. If you want to restore the default exception handler, simply use the Restore_exception_handler () function. This could also is used if your current default handler is another custom Exception class. This can also be used if you currently have a default handler that is another custom exception class. The Exception classes are held in a stack can is restored with the Restore_exception_handler () function as shown. The Exception class is Held in a stack can be restored with the Restore_exception_handler () function, as shown below.

<?php

/*** an email to validate ***/
$email = ' guru@phpro.org ';

/*** Red error Messages ***/
function Blue_default_handler ($exception) {
Echo ' <p style= ' color:blue; > '. $exception-> getMessage (). ' </p> ';
}

/*** Blue error Messages ***/
function Red_default_handler ($exception) {
Echo ' <p style= ' color:red; > '. $exception-> getMessage (). ' </p> ';
}

/*** 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 (' Invalid Email ');
}

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

if (Strpos ($email, ' Guru ')!== false)
{
throw new Exception (' Sorry, No gurus at Phpro ');
}

Echo ' is not executed ';

?>

So, from the script above we are declaration of two Exception handlers, one makes the error messags red, and the other Makes them blue. So, from the above we see two exception handling declaration scripts, where one person's error messags red, blue etc. make them. This is perhaps a abuse of the Exception functionality but serves well to demonstrate changes in classes as they. It's Xu is an abnormal function of abuse, but can well show changes in the classroom. The initial default handler is set to red. The original default handler was set to red. The A check is run to view if an $email variable is set. In the run check to see if $ email variable. Try removing the $email variable or commenting it out to see it work. Attempt to delete an e-mail dollar variable or comment out before it's working. If the $email varible is set, the code continues and the default handler are set to the Blue_default_handler. If $ e-mail varible Settings, the code continues, and the default handler is set to Blue_default_handler. Then using the Filter_var () function, the $email is tested to validity and if it fails, a blue message is shown. Then use Filte R_var () function, e-mail dollar validity is tested, if failed, a blue message is displayed. Try changing the value of the email to 1234 to the results. Try changing the value of email 1234 See the results. Finally We are the USE of Restore_exception_handler (); which pops the stack and returns the default Exception handler to the Red_default_handler. Finally, we saw Restore_exception_handle R uses the pop-up stack of (), and returns the default exception handler Red_default_handler. When all of these exceptions occur, the code execution stops and control are passed to the handler. As these exceptions occur, the execution stops and controls are passed to the handler. You are notice at the bottom of the script above and you will notice that the lines at the bottom of the scripts above
Echo ' is not executed '; Echo ' It's not executed ';
is never executed. will never be executed. But.. But. What if we wish to continue with the script and execute code below the thrown exceptions? If we want to continue with the script and execute the exception that the following code throws? This is the default behavior of exceptions. Once outside the catch () {} block your are free to include whatever code for you wish. Once captured outside () () blocks you can freely include any code wishes.

Output buffering is out by default in php.ini so it'll need to being turned on via Ob_start (). Export buffers are closed in the php.ini file by default, and therefore it needs to be closed Through the Ob_start (). We can begin output to the Brower in the script and if a exception is thrown, still use header () to redirect based on the Exception type. We can start outputting to the script brower, and if thrown an exception, still use the header () to redirect the exception type as the basis.

<?php
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.

}
catch (Pdoexception $e)
{
/*** echo the error message ***/
Echo ' }

/*** more code and HTML here ***/
Echo ' <p>catch me if you can!<p> ';

?>
Error Codes Errors code

As seen in the beginning of this document, the Exception class contains a GetCode () method that would fetch an error code, This can useful as can define your own error codes as OK as your own error messages. As you can see at the beginning of this article, the exception class contains an authentication code () method that gets the error generation Code, which can help you define your own error code, as well as your own error message. This is a quick demonstration shows. This shows how to quickly demonstrate.

<?php

/*** an invalid e-mail 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: The above code returns rows:
Error:10 Error: 10
So, big deal for you say. Well, no big deal, you say. OK, if we can define our own error codes, we could script based on thier value! well, if we could define our own error codes, scripts, we could be based on their value! The following script shows some of the possibilities. The following script shows some possibilities.

<?php

/*** an invalid e-mail 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);
}
}

?>

Related Article

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.