Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How PHP handles exceptions to Exception classes

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how the PHP exception handling Exception class, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand.

Exception is used to change the normal flow of the script when a specified error occurs. What is an anomaly? PHP 5 provides a new object-oriented approach to error handling. Exception handling is used to change the normal flow of the script when a specified error (exception) occurs. This condition is called an exception. When an exception is triggered, it usually occurs: the current code state is saved and the code execution is switched to a predefined exception handler function, depending on the situation, the processor may restart code execution from the saved code state, terminating script execution. Or continue to execute the script from another location in the code, we will show different error handling methods: the basic use of exceptions to create custom exception handlers multiple exceptions re-throw exceptions to set the top-level exception handler

Basic use of exceptions when an exception is thrown, subsequent code will not continue to execute, and PHP will try to find a matching "catch" block of code. If the exception is not caught and there is no need to use set_exception_handler () to handle it accordingly, a serious error (fatal error) occurs and an error message of "Uncaught Exception" (no exception is caught) is output. Let's try to throw an exception without catching it:

1) {throw new Exception ("Value must be 1 or below");} return true;} / / trigger exceptioncheckNum (2);? >

The above code will get an error like 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. Handling handlers should include: Try-functions that use exceptions should be in the "try" code block. If no exception is triggered, the code continues to execute as usual. But 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 catches exceptions and creates an object that contains exception information

Let's trigger an exception:

1) {throw new Exception ("Value must be 1 or below");} return true;} / / trigger exception try {checkNum (2) in "try" code block; / / If the exception is thrown, this text will not be shown echo'If you see this, the number is 1 or below';} / / catch exception catch (Exception $e) {echo 'Message:'. $e-> getMessage ();}? >

The above code will get an error like this: the Message: Value must be 1 or below example explains: the above code throws an exception and catches it:

Create the checkNum () function. It detects whether the number is greater than 1. If so, an exception is thrown. Call the checkNum () function in the "try" code block. The exception in the checkNum () function is thrown into the "catch" code block to receive the exception and create an object ($e) that contains the exception information. Output the error message from the exception by calling $e-> getMessage () from the exception object

However, in order to follow the principle that "each throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors. Creating a custom Exception class is very simple to create a custom exception handler. We have simply created a special class that can be called when an exception occurs in PHP. This class must be an extension of the exception class.

This custom exception class inherits all the properties of PHP's exception class, to which you can add custom functions. Let's start creating the exception class:

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 custom 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 properties and methods from the old class, and we can use the methods of the exception class, such as getLine (), getFile (), and getMessage (). Example explanation: the above code throws an exception and catches 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 properties and methods of the old class. Create the errorMessage () function. If the e-mail address is illegal, the function returns an error message. Set the $email variable to an illegal e-mail address string to execute the "try" code block. Because the e-mail address is illegal, an exception "catch" code block is thrown to catch the exception and display the error message.

Multiple exceptions can use multiple exceptions for a script to detect multiple situations. You can use multiple if..else code blocks, or a switch code block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

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

Example explanation: the above code tests two conditions, and 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 properties and methods of the old class. Create the errorMessage () function. If the e-mail address is illegal, the function returns an error message. Execute the "try" code block, and 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 catches exceptions and displays the appropriate error message

If the customException is not caught and the base exception is captured tightly, the exception is handled there.

Sometimes, when an exception is thrown again, 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 the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users to use, you can again throw an exception with a more user-friendly message:

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

Example explanation: the above code detects whether the e-mail address contains the string "example". If so, throw the exception again:

The customException () class is created as an extension of the old exception class. In this way, it inherits all the properties and methods of the old class. Create the errorMessage () function. If the e-mail address is illegal, the function returns an error message. Set the $email variable to a valid email address, but contain the string "example". The "try" code block contains another "try" code block so that an exception can be thrown again. Because e-mail contains the string "example", an exception is triggered. "catch" catches the exception and rethrows "customException". Capture "customException" and display an error message. If the exception is not caught in its current "try" code block, it looks for the catch code block at a higher level. Setting the top-level exception handler (Top Level Exception Handler) set_exception_handler () function sets the user-defined function that handles all uncaught exceptions.

GetMessage ();} set_exception_handler ('myException'); throw new Exception (' Uncaught Exception occurred');? >

The output of the above code should look like this: Exception: Uncaught Exception occurred in the above code, there is no "catch" code block, but instead triggers the top-level exception handler. You should use this function to catch all uncaught exceptions.

Exception rules the code that requires exception handling should be placed in the try code block to catch potential exceptions. Each try or throw code block must have at least one corresponding catch code block. Different kinds of exceptions can be caught using multiple catch code blocks. You can throw (re-thrown) the exception again in the catch code block within the try code block.

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

Thank you for reading this article carefully. I hope the article "how to deal with Exception exceptions in PHP" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report