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

PHP Try-catch statement usage tips_php tips

WBOY
Release: 2016-05-16 19:57:52
Original
1200 people have browsed it

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;>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template