Home >Backend Development >PHP Tutorial >PHP Try-catch statement usage tips, try-catch usage tips_PHP tutorial
PHP Try-catch statement
In order to further handle exceptions, we need to use try-catch statements-including Try statements 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():
<?php try { $mgr = new CommandManager(); $cmd = $mgr->getCommandObject("realcommand"); $cmd->execute(); } catch (Exception $e) { print $e->getMessage(); exit(); } ?>
As you can see, by using the throw keyword in conjunction with the try-catch statement, we can avoid "polluting" the value returned by the class method with error tags. 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.