ealeon ealeon - 3 months ago 9
Perl Question

Perl: try::tiny to catch

use strict;
use warnings;
use Date::Parse;
use Try::Tiny;

my $etime = time;
my $stime = "";
try{
my $dur = $etime - str2time($stime);
} catch {
print "error: $!\n";
};


OUTPUT

Use of uninitialized value in subtraction (-) at perl_try.pl line 10.


Anyone know how to catch this?

This is not being caught in the catch block

Answer

Try::Tiny doesn't do anything here because the message is just a warning, not an exception or error.

perldoc Date::Parse:

str2time parses DATE and returns a unix time value, or undef upon failure.

So if you want to handle a parse error in str2time, you can simply check for undef:

my $parsed_time = str2time($stime);
if (!defined $parsed_time) {
    # ... handle this case
} else {
    my $dur = $etime - $parsed_time;
    ...
}
Comments