【问题标题】:What is the PHP equivalent to Python's Try: ... Except:什么是 PHP 等价于 Python 的 Try: ... 除了:
【发布时间】:2011-04-26 18:10:26
【问题描述】:

我是一名优秀的 Python 程序员,但在 PHP 方面还不够。我需要尝试一些事情,如果这不起作用,就做其他事情。


这就是它在 Python 中的样子:

try:
      print "stuf"
except:
      print "something else"

这在 PHP 中会是什么?

【问题讨论】:

    标签: php python exception try-catch


    【解决方案1】:

    您可以使用 set_error_handler 处理 PHP 错误,就像它们是异常一样

    在这个错误处理函数中,你可以抛出各种异常,例如根据错误级别。

    通过这样做,您可以以通用方式处理任何错误(包括编程错误)。

    【讨论】:

      【解决方案2】:

      PHP 本身并不像 Python 那样支持错误捕获,除非您覆盖默认行为和 set your own error handler。 PHP 的 try - catch 是最近才在版本 5 中添加到该语言中的,它只能捕获您明确 throw 的异常。

      所以基本上,PHP 区分错误和异常。错误没有像在 Python 中那样被模块化并可供用户使用。我相信这与 PHP 最初是 collection of dynamic web scripts 的事实有关,随着时间的推移不断增长并获得更多功能,并且最近才提供改进的 OOP 支持(即版本 5);而 Python 从根本上支持 OOP 和其他元功能。以及异常处理from the beginning。

      这是一个示例用法(同样,throw 是必需的,否则不会被捕获):

      function oops($a)
      {
          if (!$a) {
              throw new Exception('empty variable');
          }
          return "oops, $a";
      }
      
      try {
          print oops($b);
      } catch (Exception $e) {
          print "Error occurred: " . $e->getMessage();
      }
      

      【讨论】:

        【解决方案3】:

        假设您正在尝试捕获异常,请查看 http://php.net/manual/en/language.exceptions.php

        你可以试试

        try {
        echo "Stuff";
        } catch (Exception $e) {
        echo "Something Else";
        }
        

        【讨论】:

          【解决方案4】:

          PHP 5 有 exception model:

          try {
              print 'stuff';
          } catch (Exception $e) {
              echo 'Caught exception: ',  $e->getMessage(), "\n";
          }
          

          【讨论】:

            【解决方案5】:
            try {
            
                // do stuff ...
            
            } catch (Exception $e) {
            
                print($e->getMessage());
            
            }
            

            见http://php.net/manual/en/language.exceptions.php

            【讨论】:

            • 这正是我所需要的,谢谢。我会在大约 8 或 9 分钟后接受这个答案。
            • @mizipzor,效果很好! @ts,抱歉我还没接受,昨晚忘记了。
            【解决方案6】:

            http://php.net/manual/en/language.exceptions.php

            try {
                print 'stuff';
            } catch (Exception $e) {
                var_dump($e);
            }
            

            注意:这仅适用于异常,不适用于错误。

            请参阅http://www.php.net/manual/en/function.set-error-handler.php。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-09-26
              • 2019-09-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-07-03
              • 2010-09-18
              • 1970-01-01
              相关资源
              最近更新 更多