Home Backend Development PHP Tutorial Summary of PHP exception handling and error handling methods

Summary of PHP exception handling and error handling methods

Jul 25, 2016 am 08:58 AM

  1. $a = fopen('test.txt','r');
  2. //The file is opened without judging it. If the file does not exist, an error will be reported
  3. ?> ;
Copy code

Correct way to write:

  1. if(file_exists('test.txt')){
  2. $f=fopen('test.txt','r');
  3. //Close after use
  4. fclose( $f);
  5. }
  6. ?>
Copy code

1. Three ways to handle PHP errors Method 1, simple die() statement; Equivalent to exit(); example:

  1. if(!file_exists('aa.txt')){
  2. die('File does not exist');
  3. } else {
  4. //Perform operation
  5. }
  6. //If above die() is triggered, then the echo connection here will not be executed
  7. echo 'ok';
Copy the code

Concise writing:

  1. file_exits('aaa.txt') or die('File does not exist');
  2. echo 'ok';
Copy code

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:

  1. if($age>120){
  2. echo 'Age Error';exit();
  3. }
  4. Use trigger:
  5. if($age>120){
  6. //trigger_error ('Error message'[,'Error level']);The error level here is optional and is used to define the level of the error
  7. //User-defined levels include the following three types: E_USER_WARNING, E_USER_ERROR, E_USER_NOTICE
  8. trigger_error('Age Error');//This is the default error handling method of the calling system. We can also use a custom processor
  9. }
  10. //Custom processor, the same as above
  11. function myerror($error_level,$error_message){
  12. echo 'error text';
  13. }
  14. //At the same time, the system default processing function needs to be changed
Copy code

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:

  1. date_default_timezone_set('PRC');
  2. function myerror($error_level,$error_message){
  3. $info= "Error number: $error_leveln";
  4. $info.= "Error message: $error_messagen";
  5. $info.= 'Occurrence time:'.date('Y-m-d H:i:s');
  6. $filename='aa.txt';
  7. if(!$fp=fopen($filename,' a')){
  8. 'Failed to create file'.$filename.';
  9. }
  10. if(is_writeable($filename)){
  11. if(!fwrite($fp,$info)){
  12. echo 'Write file failed';
  13. } else {
  14. echo 'Error message recorded successfully';
  15. }
  16. fclose($fp);
  17. } else {
  18. echo 'File'.$filename.'not writable';
  19. }
  20. exit() ;
  21. }
  22. set_error_handler('myerror',E_WARNING);
  23. $fp=fopen('aaa.txt','r');
  24. ?>
Copy code

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

  1. try{
  2. //Code that may cause errors or exceptions
  3. //catch Catching Exception is a defined exception class in PHP
  4. } catch(Exception $e){
  5. //Exception handling, method:
  6. //1. Handle it yourself
  7. //2. If you don’t handle it, throw it again
  8. }
Copy code

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:

  1. //Create a function that can throw an exception
  2. function checkNum($number){
  3. if($number>1){
  4. throw new Exception("Value must be 1 or below ");
  5. }
  6. return true;
  7. }
  8. //Trigger an exception in the "try" code block
  9. try{
  10. checkNum(2);
  11. //If the exception is thrown, then the following line of code will not be Output
  12. echo 'If you see this, the number is 1 or below';
  13. }catch(Exception $e){
  14. //Catch exception
  15. echo 'Message: ' .$e->getMessage();
  16. }
  17. ?>
Copy the code

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

  1. //Set a top exception handler
  2. function myexception($e){
  3.   echo 'this is top exception';
  4. } //Modify the default exception handling
  5. set_exception_handler("myexception");
  6. try{
  7. $i=5;
  8. if($i<10){
  9. throw new exception('$i must greater than 10');
  10. }
  11. }catch(Exception $e){

  12. //Handle exceptions
  13. echo $e->getMessage().'
    ';
  14. //Do not handle exceptions and continue to throw
  15. throw new exception('errorinfo'); //You can also use throw $e to retain the original error message;
  16. }
Copy code

Create a custom exception class

  1. class customException extends Exception{
  2.  public function errorMessage(){
  3.  //error message $errorMsg = 'Error on line '.$this->getLine().' in '. $this->getFile().': '.$this->getMessage().' is not a valid E-Mail
  4. address'; return $errorMsg;
  5. }
  6. }
  7. //Use
  8. try{
  9. Throw new customException('error message');
  10. }catch(customException $e){
  11. echo $e->errorMsg();
  12. }
Copy code

You can use multiple catches to return error information under different circumstances

  1. try{
  2.  $i=5;
  3.  if($i>0){
  4.   throw new customException('error message');//Use a custom exception class to handle
  5.   } if($i<- 10){
  6.   throw new exception('error2');//Use the system default exception handling
  7.  }
  8. }catch(customException $e){
  9.  echo $e->getMessage();
  10. }catch(Exception $e1) {
  11.  echo $e1->getMessage();
  12. }
Copy code

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.



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

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.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

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.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

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.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

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.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

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: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

See all articles