2

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($format, 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,

2 Answers 2

7

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');
Sign up to request clarification or add additional context in comments.

Comments

2

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');
}

1 Comment

This reply is a valid one too. I have tested also. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.