- // Create function with an exception
- Function checkNum ($ number)
- {
- If ($ number> 1)
- {
- Throw new Exception ("Value must be 1 or below ");
- }
- Return true;
- }
-
- // Trigger exception
- CheckNum (2 );
- ?>
The above code will get an error similar to this: Fatal error: Uncaught exception 'exception' with message 'value must be 1 or below 'in C: \ webfolder \ test. php: 6 Stack trace: #0 C: \ webfolder \ test. php (12): checkNum (28) #1 {main} thrown in C: \ webfolder \ test. php on line 6 Try, throw, and catch to avoid errors in the above example, we need to create appropriate code to handle exceptions. The handler should include: Try-use abnormal functions should be located in the "try" code block. If no exception is triggered, the code continues as usual. However, 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" Catch-"catch" code block to capture exceptions and create an object containing exception information. Let's trigger an exception:
- // Create a function that can throw an exception
- Function checkNum ($ number)
- {
- If ($ number> 1)
- {
- Throw new Exception ("Value must be 1 or below ");
- }
- Return true;
- }
-
- // Trigger an exception in the try code block
- Try
- {
- CheckNum (2 );
- // If the exception is thrown, this text will not be shown
- Echo 'If you see this, the number is 1 or below ';
- }
-
- // Capture exceptions
- Catch (Exception $ e)
- {
- Echo 'message: '. $ e-> getMessage ();
- }
- ?>
The code above will get an error similar to this: Message: Value must be 1 or below example explanation: the code above throws an exception and captures it: creates the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown. Call the checkNum () function in the "try" code block. An exception in the checkNum () function is thrown. the "catch" code block receives the exception and creates an object containing the exception information ($ e ). Call $ e-> getMessage () from this exception object to output error messages from this exception. However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors. It is very easy to create a custom Exception handler for the custom Exception class. 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:
- Class customException extends Exception
- {
- Public function errorMessage ()
- {
- // Error message
- $ ErrorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ()
- .':'. $ This-> getMessage ().'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 M message
- Echo $ e-> errorMessage ();
- }
- ?>
This new class is a copy of the old exception class, plus the errorMessage () function. Because it is a copy of the old class, it inherits attributes and methods from the old class. we can use methods of the exception class, such as getLine () and getFile () and getMessage (). The preceding code throws an exception and captures it through a custom exception class: the customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message and sets the $ email variable to an invalid email address string to execute the "try" code block, because the email address is invalid, an exception "catch" code block is thrown to capture the exception and an error message is displayed. 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:
- Class customException extends Exception
- {
- Public function errorMessage ()
- {
- // Error message
- $ ErrorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ()
- .':'. $ This-> getMessage ().'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 ();
- }
- ?>
-
The preceding code tests two conditions. if any condition is not true, an exception is thrown: the customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message. Execute the "try" code block. under the first condition, no exception is thrown. Because e-mail contains the string "example", the second condition triggers an exception. The "catch" code block captures exceptions and displays appropriate error messages. If the base mexception is not captured and the base exception is captured tightly, the exception is handled there. 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:
- 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 M message
- Echo $ e-> errorMessage ();
- }
- ?>
-
The preceding code checks whether the email address contains the string "example ". If yes, an exception is thrown again: the customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message. Set the $ email variable to a valid email address, but it contains the string "example ". The "try" code block contains another "try" code block, so that an exception can be thrown again. An exception is triggered because e-mail contains the string "example. "Catch" captures this exception and throws "customException" again ". Capture "customException" and display an error message. If an exception is not caught in its current "try" code block, it looks for the catch code block at a higher level. Top Level Exception Handler) The set_exception_handler () function can be used to process all user-defined functions without capturing exceptions.
- Function myException ($ exception)
- {
- Echo"Exception:", $ Exception-> getMessage ();
- }
-
- Set_exception_handler ('myexception ');
-
- Throw new Exception ('uncaught Exception occurred ');
- ?>
The output of the above code should be similar to this: 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. Code that requires exception handling for exception rules 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. Source: http://bbs.it-home.org/w3school/php/php_exception.html Instance:
- Function throwTest ($ data)
- {
- Try
- {
- If (! Is_array ($ data) | emptyempty ($ data ))
- {
- Throw new Exception ('data type is not an array', 445 );
- }
- Echo ('done for test !! ');
- }
- Catch (Exception $ e)
- {
- /* Echo 'error message: ', $ e-> getMessage (),'
'; // Error message
- Echo'
Error Code: ', $ e-> getCode (),' '; // Error code
- Echo'
Error File: ', $ e-> getFile (),' '; // Error file
- Echo'
Error row number: ', $ e-> getLine (),' '; // Error row number
- Echo'
The error message is displayed in an array: ', print_r ($ e-> getTrace ()),' '; // The error message is displayed in an array.
- Echo'
The error message is displayed as a string: ', $ e-> getTraceAsString (),' '; // The error message is displayed as a string */
- Echo $ e-> getMessage (),'
'; // Error message
- Echo'
', $e->getTraceAsString(), ' '; // The error message is displayed as a string
- Exit;
- }
- }
- // $ Data = array ("111", "33333"); // normal test
- $ Data = "8129233"; // exception test
- ThrowTest ($ data );
- ?>
Articles you may be interested in: example of php Exception handling exceptions: php P5 Exception handling, error throws, callback functions, and other php Exception handling, error throws, and error callback functions. a simple php custom Exception class learn php errors and exception settings |