r/PHPhelp • u/GuybrushThreepywood • Feb 15 '25
Solved Unhandled exception warnings on DateTime outside of try{} block, and in finally{}
I'm (correctly) getting a 'Unhandled \DateMalformedStringException' warning on the following code:
$dateTimeStart = new DateTime('now', new DateTimeZone('UTC')); <--- WARNING HERE
try {
<some code here>
<update db for something using $dateTimeStart>
} catch( Exception $e ) {
} finally () {
$dateTimeNowEnd = new DateTime('now', new DateTimeZone('UTC')); <--- AND HERE
$timeTaken = $dateTimeNowEnd->getTimestamp() - $dateTimeStart->getTimestamp();
echo "All done in {$timeTaken}s";
}If I move the $dateTimeStart inside the try block, the warning is replaced by '$dateTimeStart is probably not defined'.
How do I best resolve this?
2
Upvotes
3
u/Motor-Magician-1073 Feb 15 '25
Big issue :
The
finallyblock should not have parentheses (()), so change:finally () {
to
finally {
Doc -> https://www.php.net/manual/en/language.exceptions.php
5
u/allen_jb Feb 15 '25
This is a warning / "inspection" from your IDE / static analysis and won't affect runtime.
You don't always need to explicitly handle all exceptions. Here the inputs are hard coded with valid values and can be considered safe to never throw that exception.
Static analysis is always going to be somewhat opinionated and you may wish to consider modifying the level of some inspections / rules. For example, PHPStorm defaults to "warning" for a lot of inspections that should, in my opinion, be considered "nitpicks" or "potential issue, but not necessarily".
I tend to adjust the levels to something along the lines of:
3
u/colshrapnel Feb 15 '25
I promptly turned this inspection off as it just makes no sense. But does quite a harm instead, making people adding useless try-catch stuff. For example, I don't see why would you want to measure a failed database interaction.
Other methods to disable it locally are listed here.