Perl uses eval to catch exception exceptions

Source: Internet
Author: User

$ Total = 0;
$ COUNT = 0;
Eval {$ average = $ total/$ count; print "xxx/N ";};
If ($ @)
{
Print "wrong/N ";
}
Else
{
Print "right/N ";
}
 
The semicolon at the end of the eval block is required, because Eval is actually a function, unlike the if or while control structure. HoweverCodeBlocks are real blocks, so they can include lexical variables ("my" modified variables) and other arbitrary statements. Because it is a function, Eval has a return value like a subroutine (the result of the final expression, or the result returned by the Return Statement ). Of course, if a code block fails, no value is returned. If an undefined value is returned in the scalar environment, an empty list is returned in the list environment. Therefore, the safer way to calculate the average is as follows:
My $ average = eval {$ total/$ count };

Perl also supports eval code block nesting. As long as the code is executed, the eval block can always capture errors, so it can capture errors in nested subroutines. Even so, Eval cannot catch very serious errors, and Perl will interrupt the execution itself when these errors occur. These errors include uncaptured signals, memory overflow, or other disasters. Eval cannot catch syntax errors because Perl checks syntax errors when compiling eval and other code, rather than at runtime. Also, Eval cannot capture warnings. (Perl does provide a method to capture warning information. You can check the variable $ sig {__ warn __}).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.