This article mainly introduces the definition and usage of PHP exception handling to you. It analyzes the definition, usage and related precautions of PHP exception handling in more detail. Friends who need it can refer to it. I hope it can help you.
<?php //php5提供了基本的异常处理类,可直接使用 ,不需要自己再定义 // class Exception // { // protected $message = 'Unknown exception'; // 异常信息 // protected $code = 0; // 用户自定义异常代码 // protected $file; // 发生异常的文件名 // protected $line; // 发生异常的代码行号 // function __construct($message = null, $code = 0); // final function getMessage(); // 返回异常信息 // final function getCode(); // 返回异常代码 // final function getFile(); // 返回发生异常的文件名 // final function getLine(); // 返回发生异常的代码行号 // final function getTrace(); // backtrace() 数组 // final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息 // /* 可重载的方法 */ // function __toString(); // 可输出的字符串 // } ?>
<?php //定义一个顶级异常处理 function my_exception($e){ echo "我是顶级异常处理".$e->getMessage(); } //修改默认的顶级异常处理函数(器) set_exception_handler("my_exception"); //我们使用异常机制 try{ addUser("shunping"); updateUser("xiaoming1"); } //catch用来 捕获异常, Exception 是异常类(是php定义好一个类) catch(Exception $e){ //返回异常信息 echo "返回异常信息(失败信息) =".$e->getMessage()."<br/>"; echo "返回异常代码 =".$e->getCode()."<br/>"; echo "返回发生异常的文件名 =".$e->getFile()."<br/>"; echo "返回发生异常的代码行号 =".$e->getLine()."<br/>"; //echo " =".$e->getTrace()."<br/>"; // backtrace() 数组 //可以继续抛出,这时将会启动php默认的异常处理器来处理 //你也可以自己定义一个顶级异常处理器,对其进行处理 throw $e; } function addUser($username){ if($username=="shunping"){ //添加ok echo "ok1"; }else{ //添加error //抛出异常. throw new Exception("添加失败"); } } function updateUser($username){ if($username=="xiaoming"){ //正常修改 echo "ok2"; }else{ //平抛出异常 throw new Exception("修改失败"); } } ?>
Notes on abnormal use:
Through the above case, we It can be seen that using
try{ //代码 }catch(Exception $e){ //对异常处理 }
can more effectively control errors. Therefore, it is widely used in development.
1. When capturing After an exception is received, the subsequent code in the try{} block will not continue to execute.
2. If an exception occurs but you do not catch it, an Uncaught Exception.(System.)<br> will be prompted.
3. When catching an exception, you can handle it or not. If you don’t handle it, you can throw new Exception("information");
4. You You can customize the exception class
class MyException extends Exception { }
5. Use multiple catch code blocks to catch different types of exceptions
try{ //代码.... //第一句话 //第二句话 }catch(PDOException $e){ // }catch(Exception $e){ | }
6. You can also simply use Exception to capture
Code description:
<?php //定义了一个异常 class MyException1 extends Exception{ } class MyException2 extends Exception{ } function A(){ throw new MyException1("a"); } function B(){ throw new MyException2("b") } function C(){ try{ A();//抛出MyException1 B();//抛出MyException2 }catch(Exception1 $e1){ $e1->getMessage(); }catch(Exception2 $e2){ $e2->getMesage(); } } ?>
Exception rules
Required Code for exception handling should be placed within a try block to catch potential exceptions.
Each try or throw code block must have at least one corresponding catch code block.
Use multiple catch code blocks to catch different types of exceptions.
Exceptions can be thrown (thrown again) in the catch code block within the try code block.
In short: if an exception is thrown, you must catch it. Or use a top-level exception handler.
If it is not thrown, even if there is an exception, it will not be caught or processed
Related recommendations:
NodeJs database exception handling analysis
PHP7 error handling and exception handling methods
Customization of PHP exception handler
The above is the detailed content of What is PHP exception handling. For more information, please follow other related articles on the PHP Chinese website!

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

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

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

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.

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

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.

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.

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


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

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.
