简体   繁体   中英

PHP try catch block syntax

A very simple question from someone without much experience. The following try catch block has the section, "(Exception $e)" : is this like sql, where $e becomes an alias of Exception? If so, is this type of alias assignment used elsewhere in php, because I haven't come across it? I have searched for hours without being able to find an explanation on the web.

function inverse($x) {
 if (!$x) {
     throw new Exception('Division by zero.');
          }
            else return 1/$x;
          }

      try {
            echo inverse(5) . "<br/>";
            echo inverse(0) . "<br/>";
          } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "<br/>";
          }

            echo 'Hello World';

What you mention is a filter construction. It resembles a declaration as known from other, declarative languages. However it has a different meaning in fact. Actually php does not have the concept of an explicit declaration (which is a shame...).

Take a look at this example:

function my_func($x) {
    try {
        /* do something */
        if (1===$x)
            throw new SpecialException('x is 1.');
        else if (is_numeric($x))  }
            throw new SpecialException('x is numeric.');
        else return $x;
    }
    catch (SpecialException $e) {
        echo "This is a special exception!";
        /* do something with object $e of type SpecialException */
    }
    catch (Exception $e) {
        echo "This is a normal exception!";
        /* do something with object $e of type SpecialException */
    }
}

Here it becomes clear what the construction is for: it filters out by type of exception. So the question which of several catch blocks is executed can be deligated to the type of exception having been thrown. This allows a very fine granulated exception handling, where required. Without such feature only one catch block would be legal and you'd have to implement conditional tests for potential exception types in each catch block. This feature makes the code much more readable, although it is some kind of break in the php syntax.

You don't have to, but you can create own exception classes with special behavior and, more important, accepting and carrying more information about what actually happened.

It's OO PHP. The $e is an instance of the exception object.

$e could easily be labelled anything else, so long as it's referred to thereon when you want to getmessages, etc.

For instance;

 try {
        echo inverse(5) . "<br/>";
        echo inverse(0) . "<br/>";
      } catch (Exception $oops) {
        echo 'Caught exception: ',  $oops->getMessage(), "<br/>";
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM