代码段:
my $tz = DateTime::TimeZone->new(name => 'America/San_Francisco');
这会立即死亡,因为America/San_Francisco
它不是公认的时区.
打印以下消息:
无法加载时区'America/San_Francisco',或者名称无效.
我想在脚本退出之前处理此错误并为用户打印其他信息.我尝试过使用unless
,但没有运气die
.
如何才能做到这一点?
使用eval { ... }
和$@
捕获和管理致命错误.
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; }