嵌套的try catch块没有按预期工作

时间:2015-01-25 03:28:12

标签: php class exception

我有以下功能无法按预期工作。嵌套的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());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您确定zippyConstructor正在抛出ZipException吗?如果它正在抛出其他东西,那么内部捕获物会将它传递给它。