PHP exception handling related knowledge
The above code will get an error like this: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:webfoldertest.php:6 Stack trace: #0 C:webfoldertest.php(12): checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6 Try, throw and catch To avoid the errors in the above example, we need to create appropriate code to handle exceptions. Processing procedures should include: Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown. Throw - This specifies how to trigger the exception. Each "throw" must correspond to at least one "catch" Catch - The "catch" code block will catch the exception and create an object containing the exception information Let’s trigger an exception:
The above code will get an error similar to this: Message: Value must be 1 or below Example explanation: The code above throws an exception and catches it: Create checkNum() function. It detects whether the number is greater than 1. If so, throw an exception. Call the checkNum() function in the "try" block. Exception in checkNum() function is thrown The "catch" code block receives the exception and creates an object ($e) containing the exception information. Output the error message from this exception by calling $e->getMessage() from this exception object However, in order to follow the principle of "each throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors. Create a custom Exception class Creating custom exception handlers is very simple. We simply created a specialized class whose functions are called when an exception occurs in PHP. This class must be an extension of the exception class. This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it. We start creating the exception class:
This new class is a copy of the old exception class, plus the errorMessage() function. Just because it is a copy of the old class, it inherits the 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 was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message Set the $email variable to an illegal e-mail address string Execute the "try" code block and throw an exception because the e-mail address is invalid The "catch" code block catches the exception and displays the error message Multiple exceptions You 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:
Example explanation: The above code tests two conditions. If any condition is not true, an exception is thrown: The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message. Execute the "try" block of code, and in the first condition, no exception will be thrown. Since the e-mail contains the string "example", the second condition triggers an exception. The "catch" code block will catch the exception and display the appropriate error message If customException is not caught and base exception is caught tightly, the exception is handled there. Rethrow the exception Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. The exception can be thrown again in a "catch" 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, you can throw the exception again with a user-friendly message:
Example explanation: The above code detects whether the string "example" is contained in the email address. If so, throw the exception again: The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message. Set the $email variable to a valid email address, but containing the string "example". A "try" block contains another "try" block so that the exception can be thrown again. The exception is triggered because the e-mail contains the string "example". "catch" catches the exception and rethrows "customException". A "customException" is caught and an error message is displayed. If the exception is not caught in its current "try" block, it will look for a catch block at a higher level. Set the Top Level Exception Handler The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.
The output of the above code should be similar to this: Exception: Uncaught Exception occurred In the above code, there is no "catch" block, instead the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions. unusual rules Code that requires exception handling should be placed within a try block to catch potential exceptions. Every try or throw block must have at least one corresponding catch block. Use multiple catch blocks to catch different kinds of exceptions. Exceptions can be re-thrown in a catch block within a try block. In short: if an exception is thrown, you must catch it. Source: http://bbs.it-home.org/w3school/php/php_exception.html Example:
Articles you may be interested in: Example of using php exception handling class Exception PHP5 exception handling, error throwing and callback functions, etc. Exception handling, error throwing and error callback functions in php A simple php custom exception class Learn php errors and exception settings |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.
