PHP's exception handling mechanism is very similar to Java, but there is no finally, but also can customize the top-level exception handler, after catching the exception information, will jump out of the try-catch block, if there is no jump in the catch action, will continue to execute the next statement.
Simple Exception Capture:
1<?PHP2 functionAddUser ($name)3 {4 if($name= = "Zheng")5 {6 Echo"Added successfully! <br/> ";7 }8 Else9 {Ten Throw New Exception("Add failed! <br/> "); One } A } - - functionUpdateUser ($name) the { - if($name= = "Song") - { - Echo"The update is successful!" <br/> "; + } - Else + { A Throw New Exception("Update failed!") <br/> "); at } - } - Try -{UpdateUser ("xx"); -AddUser ("Zheng"); - in } - Catch(Exception $e) to { + Echo"Caught the exception information! ".$e-getMessage (); - } the EchoHello; *?>View Code
By inheriting the exception class, you can customize the exception class, implement custom exceptions, and catch different types of exceptions to implement different processing mechanisms.
1<?PHP2 //This program can be implemented to catch different exceptions! 3 classException1extends Exception4 {5 6 }7 classException2extends Exception 8 {9 Ten } One A //$x =1; - $x=2; - Try the { - if($x==1) - { - Throw NewException1 ("Exception information 1"); + } - Else + { A Throw NewException2 ("Exception information 2"); at } - } - Catch(Exception1$e 1) - { - Echo"Captured".$e 1->getmessage (). "!"; - } in Catch(Exception2$e 2) - { to Echo"Captured".$e 2->getmessage (). "!"; + } -?>View Code
The Set_exception_handler method allows you to customize the system's default exception handler, which we can think of as the top-level exception handler, which is automatically called when an exception occurs.
1<?PHP2 functionMyException ($e)3 {4 Echo"This is the top-level exception handler!" The exception handler that handles exceptions by default when no capture is in progress! <br/> exception information is: ".$e-getMessage ();5 }6 Set_exception_handler("MyException");7 8 Throw New Exception("There was a program exception!") ");9?>View Code
Finally, there is a bug in PHP's exception handling mechanism (PHP5.3.5):
In the following case PHP will not catch the exception, but the direct error.
1<?PHP2 //PHP two classic bugs3 Try4 {5 $a=8/0;6 }7 Catch(Exception $e)8 {9 Echo"Exception message capture succeeded!" <br/> ";Ten } One A Try - { - $file=fopen("Xxx.txt", "r+"); the } - Catch(Exception $e) - { - Echo"Exception message capture succeeded!" <br/> "; + } - +?>View Code
"Exception Handling in PHP" full ""