Summary of PHP exception handling and error handling methods
Correct way to write:
1. Three ways to handle PHP errors Method 1, simple die() statement; Equivalent to exit(); example:
Concise writing:
Method 2, custom errors and error triggers 1. Error handler (custom error, generally used for syntax error handling) Create a custom error function (handler) that must be able to handle at least two parameters (error_level and errormessage), but can accept up to five parameters (error_file, error_line, error_context) grammar: function error_function($error_level,$error_message,$error_file,$error_line,$error_context) //After creation, you need to rewrite the set_error_handler(); function set_error_handler(‘error_function’,E_WARNING); //Here error_function corresponds to the custom handler name created above, and the second parameter is the error level using the custom error handler; Error reporting level (just understand it) These error reporting levels are the different types of errors that error handlers are designed to handle: Value Constant Description 2 E_WARNING Nonfatal run-time error. Do not pause script execution. 8 E_NOTICE Run-time notifications. Script discovery errors may occur, but they may also occur while the script is running normally. 256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error(). 512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error(). 1024 E_USER_NOTICE User-generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). 4096 E_RECOVERABLE_ERROR Trapable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (see set_error_handler()) 8191 E_ALL All errors and warnings except level E_STRICT. (In PHP 6.0, E_STRICT is part of E_ALL) 2. Error trigger (generally used to handle logical errors) Requirement: For example, if you want to receive an age, if the number is greater than 120, it is considered an error. Traditional method:
set_error_handler('myerror',E_USER_WARNING);//Same as above, the first parameter is the name of the custom function, and the second is the error level [The error levels here are usually the following three :E_USER_WARNING, E_USER_ERROR, E_USER_NOTICE] //Now you can use trigger_error to use a custom error handling function Practice questions:
Method 3, error log By default, according to the error_log configuration in php.ini, php sends error records to the server's error recording system or file. Error records can be sent to a file or remote destination by using the error_log() function; grammar: error_log(error[,type,destination,headers]) The type part generally uses 3, which means appending error information to the end of the file without overwriting the original content. destination represents the destination, that is, the stored file or remote destination For example: error_log(“$error_info”,3,”errors.txt”); 2. PHP exception handling 1. Basic grammar
2. The processing handler 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” block catches the exception and creates an object containing the exception information Trigger an exception:
The above code will report an error like this: Message: Value must be 1 or below Explanation: The above code 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 "every throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors. set_exception_handler() function can set a user-defined function that handles all uncaught exceptions
Create a custom exception class
You can use multiple catches to return error information under different circumstances
Rules for using exceptions: 1. Put the code that needs exception handling into the try code block to catch potential exceptions. 2. Each try or throw code block must have at least one corresponding catch code block. 3. Use multiple catch code blocks to catch different types of exceptions. 4. The exception can be re-thrown in the catch code block within the try code. Remember one sentence: If an exception is thrown, you must catch it. |

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











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.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
