我怎么能处理一个死的perl构造函数?

时间:2017-01-09 17:17:07

标签: perl error-handling die

代码段:

America/San_Francisco

这会立即死亡,因为unless不是recognized timezone

打印以下信息:

时区' America / San_Francisco'无法加载,或者名称无效。

我想在脚本退出之前处理此错误并为用户打印其他信息。我尝试使用die,但没有运气抓住(defn deque ([] '[()()]) ([& elems] [elems '()])) (defn push-front [deque elem] (let [[head tail] deque] [(cons elem head) tail])) (defn push-back [deque elem] (let [[head tail] deque] [head (cons elem tail)])) (defn pop-front [deque] (let [[head tail] deque] (if (empty? head) [(-> tail reverse rest) head] [(rest head) tail]))) (defn pop-back [deque] (let [[head tail] deque] (if (empty? tail) [tail (-> head reverse rest)] [head (rest tail)]))) (defn peek-front [deque] (let [[head tail] deque] (if (empty? head) (-> tail reverse first) (first head)))) (defn peek-back [deque] (let [[head tail] deque] (if (empty? tail) (-> head reverse first) (first tail)))) ;; usage example: user> (let [dq (deque )] (-> dq (push-front :a) (push-front :b) (peek-back))) :a user> (let [dq (deque )] (-> dq (push-front :a) (push-front :b) (pop-back))) [() (:b)] user> (let [dq (deque )] (-> dq (push-back :a) (push-back :b) (peek-back))) :b

如何做到这一点?

1 个答案:

答案 0 :(得分:5)

使用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;
}