在 PHP v 5.6 中,我如何捕获 UnexpectedValueException?

In PHP v 5.6 how do I catch UnexpectedValueException?

我查看了多种确定目录是否为空的方法,许多表明 $isDirEmpty = !(new \FilesystemIterator($dir))->valid(); 是一个不错的选择,除了 $ 中的目录路径dir 参数必须存在,否则会抛出 UnexpectedValueException。有关使用此方法的更多详细信息,请参阅 How can I use PHP to check if a directory is empty?

然而,这个和其他示例首先需要使用其他 functions/statements 来确定目录是否存在,然后再使用 FileSystemIterator 检索迭代器并测试其项目,但是这些通常缓存有关目录的信息并且需要在使用后明确释放,其中许多示例都没有这样做。

为了绕过这些额外的 'details' 并帮助我进行调试,我决定在使用 try/catch 块而不是有效 [=15 的函数中实现 FileSystemIterator 技术=] 如果文件系统项是 valid(不管那是什么意思)或 false,returns 是真的,我正在使用 getPathname 方法,所以我可以看到我调试代码时的实际 directory/file 路径名。

这是我的函数,但我需要 catch() 参数来完成它:

function isDirectoryEmpty( $dir ) {

    //
    // Create a file system iterator from the directory path and get the first
    // directory content item, if one exists,  Note, FilesystemIterator ignores
    // the special . and .. entries in a directory that always exist, so I don't
    // need to filter them out with code.

    try {

        $iterator = new \FilesystemIterator( $dir );

        foreach( $iterator as $fileinfo ) {

            $filePathName = $fileinfo->getPathname();
            break;

        }

    }
    catch( WHAT_GOES_HERE ) {

        $filePathName = '';

    }

    return  ( $filePathName === '' );

}

因为我只需要一个现有的目录成员来证明目录不为空,所以我跳出了 foreach 从迭代器获取文件信息的块,但如果我知道如何在没有 foreach 循环语句的情况下执行此操作。有人也可以给我执行此操作的代码吗?

更新

foreach循环可以替换如下:

$filePathName = ''; // Assume that the $dir directory is empty, even if it
                    // doesn't exist and the FilesystemIterator creation
                    // method throws an exception.

try {

    $filePathName = ( new \FilesystemIterator( $dir ) )->getPathname();

}
catch( UnexpectedValueException $exception ) {} // Other than catching the
                                                // exception, no other action
                                                // is needed.

谢谢。

如果您得到的异常是 UnexpectedValueException,您可以像这样在 catch 语句中指定它的类型来捕获它:

try {
     // some logic
} catch( UnexpectedValueException $exception) {
    // Print the exception message
    echo 'Message: ' .$exception->getMessage(); 
}