例外情况

Zephir以非常低的级别实现异常,为PHP提供类似的行为和功能。

抛出异常时,可以使用 catch 块来捕获异常并允许开发人员提供正确的处理:

可以在try语句中抛出异常。 和PHP一样,在catch中捕获异常并处理

  1. var e;
  2. try {
  3. throw new \Exception("This is an exception");
  4. } catch \Exception, e {
  5. echo e->getMessage();
  6. }

Zephir 还提供了一个“安静”try语句,用来忽略产生的任何异常:

  1. try {
  2. throw new \Exception("This is an exception");
  3. }

如果在<0>catch</0>中不处理异常,可以不提供异常变量:

  1. try {
  2. throw new \Exception("This is an exception");
  3. } catch \Exception {
  4. echo "An exception occur!";
  5. }

catch中捕获多个异常:

  1. var e;
  2. try {
  3. throw new \Exception("This is an exception");
  4. } catch \RuntimeException|\Exception, e {
  5. echo e->getMessage();
  6. }

Zephir允许您抛出文字或静态类型变量,就像它们是异常的消息一样:

  1. // throw new \Exception("Test");
  2. throw "Test";
  3. // throw new \Exception((string) 't');
  4. throw 't';
  5. // throw new \Exception((string) 123);
  6. throw 123;
  7. // throw new \Exception((string) 123.123);
  8. throw 123.123;
  9. ```zephir
  10. Zephir's exceptions provide the same methods to know where the exception happened that PHP's exceptions do. That is, `Exception::getFile()` and `Exception::getLine()` return the location in the Zephir code where the exception was thrown:
  11. ```bash
  12. Exception: The static method 'someMethod' does not exist on model 'Robots'
  13. File=phalcon/mvc/model.zep Line=4042
  14. #0 /home/scott/test.php(64): Phalcon\Mvc\Model::__callStatic('someMethod', Array)
  15. #1 /home/scott/test.php(64): Robots::someMethod()
  16. #2 {main}