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

Summary of PHP exception handling and error handling methods

WBOY
WBOYOriginal
2016-07-25 08:58:021037browse
  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:
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