duanping2809 2015-02-17 22:28
浏览 162
已采纳

Exception会终止程序吗?

Considering the following code, run by cron:

try {
    $count = $stmt->execute ( $queryArray );
}
catch ( PDOException $ex ) {
    fwrite ( $fp, '  "exception" at line: ' . (__LINE__ - 3). ",  " . $ex -> getMessage () . "
" );
    throw new RuntimeException (
         basename (__FILE__) . '::' . __METHOD__ . ' - Execute query failed: ' . $ex -> getMessage ()  );
}

Is re-throwing by throw new RuntimeException causing the program to stop? In other words, would the catch & fwrite statement sufficiently 'catch' the exception and allow the program to continue?

The throw documentation is vague. The only reference is to PHP Fatal Error from (link to) PHP Exceptions:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

  • 写回答

1条回答 默认 最新

  • dongyan1841 2015-02-17 22:46
    关注

    Is re-throwing by throw new RuntimeException causing the program to stop?

    Yes, because as per the documentation there is no matching catch. In order to continue execution you would need to catch the second exception (RuntimeException) by using a nested try/catch which is generally not a great idea:

    try {
       // something with PDO that generates an exception
    } catch (PDOException $e) {
       // do some stuff
       try {
           throw new RuntimeException();
       } catch (RuntimeException()) {
         // do something else
       }
    }
    

    In other words, would the catch & fwrite statement sufficiently 'catch' the exception and allow the program to continue?

    If you want to continue with the program then you would need to not throw the second exception. However, anything that happened before you throw that exception will occur. So in your example the fwrite would still happen, the program would just be halted when the RuntimeException is encountered.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?