【问题标题】:PHP try catch skipping catch, directly jumping into finallyPHP try catch 跳过catch,直接跳入finally
【发布时间】:2017-09-11 03:34:34
【问题描述】:

好吧,我很困惑。我正在使用 Slim 框架,并且我有以下代码:

1 $app->post("/user/login", function (Request $request, Response $response) {
2    $resp = null;
3    try {
4       if (!array_key_exists("password", $request->getParams()) || !array_key_exists("username", $request->getParams())) {
5            throw new LiberInvalidRequestException("Not all required parameters were passed.");
6        }
7        $user = new User($this->db, [
8            'username' => $request->getParam('username'),
9            'password' => $request->getParam('password')
10        ]);
11        try {
12            $resp['logincode'] = $user->login();
13            $resp['success'] = true;
14        } catch (LiberAuthenticationException $exception) {
15            $resp['success'] = false;
16            $resp['errormessage'] = $exception->getMessage();
17        }
18    } catch (LiberInvalidRequestException $exception) {
19        $resp['success'] = false;
20        $resp['errormessage'] = $exception->getMessage();
21    } finally {
22        return $response->withJson($resp);
23    }
24 });

当我用正确的参数调用这条路线时,我得到一个null 响应。在我看来,这不应该是可能的,因为在所有可能的情况下,某些东西都分配给了$resp。当我使用调试器执行此函数时,我可以一直运行到第 12 行,然后调试器会跳转到 finally 块(第 22 行)。

这怎么可能?执行不应该继续还是转到catch块?

【问题讨论】:

  • 如果抛出LiberAuthenticationException 或LiberInvalidRequestException 以外的一些异常,可能会出现...命名空间问题?
  • @deceze 我认为没有抛出另一个异常。我发现执行跳转到finally块的点是composer autoloader中的一个include语句。包含语句不会抛出异常 IIRC。
  • try 内的 try 只会增加混乱。请参阅 this 帖子,了解如何为单个 try 编写多个 catch 块 - 如果需要的话。
  • @DhruvSaxena 您发布链接的问题是关于如何在一个块中编写多个捕获。我有多个尝试块做不同的事情。我也不认为这与我的问题有很大关系。

标签: php try-catch try-catch-finally


【解决方案1】:

好的,我找到了问题的解决方案。正如@deceze 所说,抛出了一个捕获块没有捕获的异常。由于我使用 PHP7.1 包含语句可以抛出异常。这就是首先抛出异常的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2014-11-27
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    相关资源
    最近更新 更多