search
HomeBackend DevelopmentPHP TutorialSummary of PHP exception handling and error handling methods

  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($ithrow new exception('$i must greater than 10');
  9. }> ;
  10. }catch(Exception $e){

  11. //Handle exceptions
  12. echo $e->getMessage().'
    ';
  13. //Do not handle exceptions and continue to throw
  14. throw new exception('errorinfo'); //You can also use throw $e to retain the original error message;
  15. }
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   throw new exception('error2');//Use the system default exception handling
  6.  }
  7. }catch(customException $e){
  8.  echo $e->getMessage();
  9. }catch(Exception $e1) {
  10.  echo $e1->getMessage();
  11. }
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor