Home  >  Article  >  Backend Development  >  PHP Try-catch statement usage tips_php tips

PHP Try-catch statement usage tips_php tips

WBOY
WBOYOriginal
2016-05-16 19:57:521167browse

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():

<&#63;php 
try { 
  $mgr = new CommandManager(); 
  $cmd = $mgr->getCommandObject("realcommand"); 
  $cmd->execute(); 
} catch (Exception $e) { 
  print $e->getMessage(); 
  exit(); 
} 
&#63;>

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn