繁体   English   中英

如何在PHP,DateTime :: createFromFormat()上抛出异常?

[英]How can I throw exception on PHP, DateTime::createFromFormat()?

我是一个关于抛出Exceptions的新手,我在使用这个PHP基本方法时没有得到如何抛出异常,DateTime :: createFromFormat()

案例如下:

private function obtainMostRecentFile($fileNamesArray, $start, $lenght) {
    foreach ($fileNamesArray as $row) {
        $i++;
        $format = 'Ymd';
        $date = DateTime::createFromFormat($format, substr($row, $start, $lenght));
        $date_in_format[$i] = $date->format('Ymd');
    }
    return (max($date_in_format));
}

我有这个方法,我需要找到一种在DateTime::createFromFormat($format, substr($row, $start, $lenght));时抛出异常的方法DateTime::createFromFormat($format, substr($row, $start, $lenght)); 运行不正常。

例如:

如果我调用$this->obtainMostRecentFile("GeoLiteCity_20101201.zip", 12, 8); 该函数返回它们应返回的输出。

如果我调用$this->obtainMostRecentFile("GeoLiteCity_201.zip", 12, 8); 函数返回输出Fatal error: Call to a member function format() on a non-object in C:\\xampp\\htdocs\\testes\\testecsv4.php on line 440

Normaly我做这样的事情:

if (is_null($someVariable)) {
    throw new Exception("null variable");
}

你能给我一些关于如何为DateTime::createFromFormat()抛出Exception的线索吗?

最好的祝福,

当使用无效值调用DateTime::createFromFormat ,它会返回false false没有方法format ,因此这是您的应用程序崩溃的地方:

$date_in_format[$i] = $date->format('Ymd');

你应该在那之前加上一张支票:

$format = 'Ymd';
$date = DateTime::createFromFormat($format, substr($row, $start, $lenght));
if($date === false) {
    // throw an exception here!
}
$date_in_format[$i] = $date->format('Ymd');

在你没有正确运行DateTime::createFromFormat情况下,它会返回一个不是对象的东西(可能是布尔值false )。 检查该变量,如果它不是对象,则抛出异常

$date = DateTime::createFromFormat($format, substr($row, $start, $lenght)); 
if (!is_object($date)) { // or $date === false
    throw new Exception('DateTime::createFromFormat error');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM