【问题标题】:nested try catch block not working as expected嵌套的 try catch 块没有按预期工作
【发布时间】:2015-03-23 20:24:04
【问题描述】:

我的以下功能没有按预期工作。在嵌套的 try 块(包含 zippyConstructor)中抛出了一个错误,但是错误不是通过 unlink 命令转到相应的 catch 块,而是转到外部的 catch 块,绕过了一些内置的安全防护(例如删除一个坏文件)。关于嵌套的 try catch 块,我有什么遗漏吗?

public function doBackup($rethrow = false)
{
    try {

        $filename = 'dbbackup_' . date(str_replace('-', '.', DATE_FORMAT) . '_H_i_s');

        $tables = $this->tablesToBackup();

        $data = $this->mysqlDump($tables);

        $this->createSaveDir();

        $sqlFile = $this->dir_sql . $filename . '.sql';
        $handle = @fopen($sqlFile, 'w+');

        if (!$handle) {
            throw new Exception ("Could not open: {$sqlFile}");
        }

        if (@fwrite($handle, $data) === FALSE) {
            throw new Exception ("Could write: {$sqlFile}");
        }

        try {

            $this->zippyConstructor($this->dir_files . $filename . '.zip', $this->folders_to_backup, $sqlFile);

            @fclose($handle);

            if (!$rethrow) {
                $this->msg->add('s', "Backup {$filename} successfully created.");
            }

        } catch (ZipException $e) {

            @fclose($handle);

            // remove corrupted files
            is_file($sqlFile) ? @unlink($sqlFile) : '';
            is_file($this->dir_files . $filename . '.zip') ? @unlink($this->dir_files . $filename . '.zip') : '';

            if ($rethrow) {
                throw $e;
            } else {
                $this->msg->add('e', 'Inner_Catch Backup failed: <br>' . $e->getMessage());
            }

        }
    } catch (Exception $e) {

        @fclose($handle);

        if ($rethrow) {
            throw $e;
        } else {
            $this->msg->add('e', 'Outer_Catch Backup failed: <br>' . $e->getMessage());
        }
    }
}

【问题讨论】:

    标签: php class exception


    【解决方案1】:

    你确定 zippyConstructor 会抛出 ZipException 吗?如果它在扔别的东西,内部的捕获物会把它向上传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 2019-05-26
      相关资源
      最近更新 更多