in
try
{ //...}
catch(Exception $e)
{ //...}
try{}catch{} in PHP is exception handling.
Put the code to be executed into the TRY block. If an exception occurs in a certain statement during the execution of these codes, the program will jump directly In the CATCH block, $e collects error information and displays it.
try{}catch{} statement in PHP
In order to further handle the exception, we need to use PHP The try{}catch{}----includes the Try statement and at least one catch statement. Any code that calls a method that may throw an exception should use a try statement. The Catch statement is used to handle exceptions that may be thrown. The following shows how we handle exceptions thrown by getCommandObject():
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><</span><span> ?php </span></span></li><li><span>try { </span></li><li class="alt"><span>$</span><span class="attribute">mgr</span><span> = </span><span class="attribute-value">new</span><span> CommandManager(); </span></li><li><span>$</span><span class="attribute">cmd</span><span> = $mgr-</span><span class="tag">></span><span>getCommandObject("realcommand"); </span></span></li> <li class="alt"> <span>$cmd-</span><span class="tag">></span><span>execute(); </span> </li> <li><span>} catch (Exception $e) { </span></li> <li class="alt"> <span>print $e-</span><span class="tag">></span><span>getMessage(); </span> </li> <li><span>exit(); </span></li> <li class="alt"><span>} </span></li> <li> <span class="tag">?></span><span> </span> </li> </ol>
As you can see, by combining the throw keyword with try in PHP {}catch{}, we can avoid mislabeling "polluting" the values returned by class methods. Because "exception" itself is a PHP built-in type that is different from any other object, there will be no confusion.
If an exception is thrown, the script in the try statement will stop executing, and then immediately switch to executing the script in the catch statement.
If an exception is thrown but not caught, a fatal error will be generated.