2

Code snippet:

my $tz = DateTime::TimeZone->new(name => 'America/San_Francisco'); 

This immediately dies because America/San_Francisco is not a recognized timezone.

The following message is printed:

The timezone 'America/San_Francisco' could not be loaded, or is an invalid name.

I would like to handle this error and print additional info for the user before the script exits. I tried using unless, but no luck catching the die.

How can this be done?

1 Answer 1

5

Use eval { ... } and $@ to trap and manage fatal errors.

my $tz = eval { DateTime::TimeZone->new(name => 'America/San_Francisco') }; if (!$tz) { if ($@ =~ /The timezone .* could not be loaded/) { warn "Choose a timezone from ", "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List"; } else { warn "Error in DateTime::TimeZone constructor: $@"; } exit 1; } 
Sign up to request clarification or add additional context in comments.

5 Comments

This almost works, but gives me a strange error: Choose a timezone from https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List at ./test-die.pl line 6, <DATA> line 1.
my $tz; eval { $tz = .... ; 1 } or do { if ($@ =~ is safer. $@ might be clobbered in some Perl versions. See Try::Tiny and Bug in eval in pre-5.14.
@JonathanCross Add a \n to the end of the string to prevent the location from being included.
Try::Tiny is safer than evals.
@choroba, my $tz = eval { ... } or do { ... }; would suffice since DateTime::TimeZone->new always returns a true value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.