This article mainly introduces the definition and usage of PHP exception handling. It analyzes the definition, usage and related precautions of PHP exception handling in more detail. Friends in need can refer to it
The details are as follows:
getMessage(); } //修改默认的顶级异常处理函数(器) set_exception_handler("my_exception"); //我们使用异常机制 try{ addUser("shunping"); updateUser("xiaoming1"); } //catch用来 捕获异常, Exception 是异常类(是php定义好一个类) catch(Exception $e){ //返回异常信息 echo "返回异常信息(失败信息) =".$e->getMessage()."
"; echo "返回异常代码 =".$e->getCode()."
"; echo "返回发生异常的文件名 =".$e->getFile()."
"; echo "返回发生异常的代码行号 =".$e->getLine()."
"; //echo " =".$e->getTrace()."
"; // 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 using exceptions:
From the above case, we can see that usingtry{ //代码 }catch(Exception $e){ //对异常处理 }
2. If an exception occurs but you do not catch it, an
Uncaught will be prompted. Exception.(System.)
3. When catching an exception, you can handle it or not. If you don’t handle it, you can
throw new Exception("information");
class MyException extends Exception { }
try{ //代码.... //第一句话 //第二句话 }catch(PDOException $e){ // }catch(Exception $e){ | }
getMessage(); }catch(Exception2 $e2){ $e2->getMesage(); } } ?>
Exception rules
Code that requires exception handling should be placed in a try code 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 handled
PHP exception handlingSharing error handling methods
What isPHP exception handling
## Customization of PHP exception handler
The above is the detailed content of Detailed explanation of the definition and usage of PHP exception handling. For more information, please follow other related articles on the PHP Chinese website!