The 13th chapter: error Handling one Lu Ying.
to throw an exception, do not return a special value or set a tag. One Qi 0.
Let the failed built-in function also throw an exception. one Qi one.
all failures in the context are fatal failures.
#把不可接受的失败行为改为抛出异常 ...
Usefatal QW (: void Locate_and_open);
#稍后 ...
Formy $filename () {
MY$FH = Locate_and_open ($filename);
My$head = Load_header_from ($FH);
Print$head;
} One and seven.
be careful when testing the failure of system built-in functions.
Useposix QW (wifexited);
#稍后 ...
Wifexited (System$cmd)
Orcroak "couldn ' t run: $cmd ($OS _error)"; One Qi three.
throws an exception for all failures, including a resilient failure.
TRY:
Formy $try (1.. $MAX _tries) {
#如果资源成功地取得, it's done ...
eval{
$resource = Acquire_resource ($resource _id);
Lasttry;
};
#如果不再尝试 to report an unrecoverable failure
Croak ($EVAL _error) if $try = = $MAX _tries;
#不然就在随机拉长的时间间距后再试一次 ...
NAP (Rand Fibonacci ($try)); Ghd
}
Do_something_using ($resource); One Qi restaurant.
report the exception from the location of the caller, not from the place where the exception was thrown. one Qi Wu.
write error messages in the dialect of the recipient. One Qi Lu.
Write a description document for each error message in the recipient's dialect. One Qi Qi.
the exception object is used whenever the failed data must be passed to the handler. One qi Ba.
the exception object should be used when the error message is likely to change. One Qi Jiu.
When two or more exceptions are related to each other, the exception object should be used. one BA 0.
The exception object is captured in the order of MDF (Most-derived-first, lowest derived first). one BA.
automatically establishes the exception class. one BA Ii.
Remove the exception variable within the extended exception handler.
Perl Best Practices (excerpt)---13