How can I throw exception on PHP, DateTime::createFromFormat()?
I'm a newbie on throwing Exceptions and I'm not getting how to throw an Exception when using this PHP base method, DateTime::createFromFormat()
The case is the following:
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));
}
I have this method, and I need to find a way of throwing an Exception when the DateTime::createFromFormat($fo开发者_运维知识库rmat, substr($row, $start, $lenght));
does not run correctly.
For example:
If I call $this->obtainMostRecentFile("GeoLiteCity_20101201.zip", 12, 8);
the function return the output that they should return.
If I call $this->obtainMostRecentFile("GeoLiteCity_201.zip", 12, 8);
the function return the output Fatal error: Call to a member function format() on a non-object in C:\xampp\htdocs\testes\testecsv4.php on line 440
.
Normaly I do something like this:
if (is_null($someVariable)) {
throw new Exception("null variable");
}
Can you give me some clues on how to thrown Exception for the DateTime::createFromFormat()
?
Best regards,
When DateTime::createFromFormat
is called with an invalid value, it returs false
. false
does not have a method format
, so this is where your app breaks down:
$date_in_format[$i] = $date->format('Ymd');
You should include a check before that:
$format = 'Ymd';
$date = DateTime::createFromFormat($format, substr($row, $start, $lenght));
if($date === false) {
// throw an exception here!
}
$date_in_format[$i] = $date->format('Ymd');
In your case when DateTime::createFromFormat
is not run correctly it returns something that is not an object (probably boolean false
). Check that variable and throw Exception if it's not an object
$date = DateTime::createFromFormat($format, substr($row, $start, $lenght));
if (!is_object($date)) { // or $date === false
throw new Exception('DateTime::createFromFormat error');
}
精彩评论