⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch10_13.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 10.12. Handling Exceptions (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:40:00Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch10_01.htm"TITLE="10. Subroutines"><LINKREL="prev"HREF="ch10_12.htm"TITLE="10.11. Prototyping Functions"><LINKREL="next"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_12.htm"TITLE="10.11. Prototyping Functions"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.11. Prototyping Functions"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch10_01.htm"TITLE="10. Subroutines"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.13. Saving Global Values"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch10-34783">10.12. Handling Exceptions</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-944">Problem</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch10-idx-1000004720-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004720-1"></A><ACLASS="indexterm"NAME="ch10-idx-1000004720-2"></A>How do you safely call a function that might raise an exception? How do you create a function that raises an exception?</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-950">Solution</A></H3><PCLASS="para">Sometimes you encounter a problem so exceptional that merely returning an error isn't strong enough, because the caller could ignore the error. Use <CODECLASS="literal">die</CODE><ACLASS="indexterm"NAME="ch10-idx-1000004721-0"></A> <CODECLASS="literal">STRING</CODE> from your function to trigger an exception:</P><PRECLASS="programlisting">die &quot;some message&quot;;         # raise exception</PRE><PCLASS="para">The caller can wrap the function call in an <CODECLASS="literal">eval</CODE> to intercept that exception, and then consult the special variable <CODECLASS="literal">$@</CODE> to see what happened:</P><PRECLASS="programlisting">eval { func() };if ($@) {    warn &quot;func raised an exception: $@&quot;;} </PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-968">Discussion</A></H3><PCLASS="para">Raising exceptions is not a facility to be used lightly. Most functions should return an error using a bare <CODECLASS="literal">return</CODE> statement. Wrapping every call in a trap is tedious and unsightly, removing the appeal of using exceptions in the first place.</P><PCLASS="para">But on rare occasion, failure in a function should cause the entire program to abort. Rather than calling the irrecoverable <CODECLASS="literal">exit</CODE> function, you should call <CODECLASS="literal">die</CODE> instead, which at least gives the programmer the chance to cope. If no exception handler has been installed via <CODECLASS="literal">eval</CODE>, then the program aborts at that point.</P><PCLASS="para">To detect such a failure program, wrap the call to the function with a block <CODECLASS="literal">eval</CODE>. The <CODECLASS="literal">$@</CODE> variable will be set to the offending exception if one occurred; otherwise, it will be false.</P><PRECLASS="programlisting">eval { $val = func() };warn &quot;func blew up: $@&quot; if $@;</PRE><PCLASS="para">Any <CODECLASS="literal">eval</CODE> catches all exceptions, not just specific ones. Usually you should propagate unexpected exceptions to an enclosing hander. For example, suppose your function raised an exception containing the string <CODECLASS="literal">&quot;Full</CODE> <CODECLASS="literal">moon!&quot;</CODE>. You could safely trap that exception while letting the others through by inspecting the <CODECLASS="literal">$@</CODE> variable. Calling <CODECLASS="literal">die</CODE> without an argument uses the contents of <CODECLASS="literal">$@</CODE> and the current context to construct a new exception string.</P><PRECLASS="programlisting">eval { $val = func() };if ($@ &amp;&amp; $@ !~ /Full moon!/) {    die;    # re-raise unknown errors}</PRE><PCLASS="para">If the function is part of a module, consider using the Carp module and call <CODECLASS="literal">croak</CODE> or <CODECLASS="literal">confess</CODE> instead of <CODECLASS="literal">die</CODE>. The only difference between <CODECLASS="literal">die</CODE> and <CODECLASS="literal">croak</CODE> is that with <CODECLASS="literal">croak</CODE>, the error appears to be from the caller's perspective, not the module's. The <CODECLASS="literal">confess</CODE> function, on the other hand, creates a full stack backtrace of who called whom and with what arguments.</P><PCLASS="para">Another intriguing possibility is for the function to detect that its return value is being completely ignored; that is, it is being called in a void context. In that case, returning an error indication would be useless, so raise an exception instead.</P><PCLASS="para">Of course, just because it's not voided doesn't mean the return value is being dealt with appropriately. But if it is voided, it's certainly not being checked.</P><PRECLASS="programlisting">if (defined wantarray()) {        return;} else {    die &quot;pay attention to my error!&quot;;}<ACLASS="indexterm"NAME="ch10-idx-1000004723-0"></A><ACLASS="indexterm"NAME="ch10-idx-1000004723-1"></A><ACLASS="indexterm"NAME="ch10-idx-1000004723-2"></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch10-pgfId-1008">See Also</A></H3><PCLASS="para">The <ACLASS="olink"HREF="../prog/ch02_09.htm#PERL2-CH-2-SECT-9.3"><CODECLASS="literal">$@</CODE></A> variable in <ACLASS="olink"HREF="../prog/ch02_01.htm">Chapter 2</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and <ICLASS="filename">perlvar </I>(1); the <ACLASS="olink"HREF="../prog/ch03_027.htm"><CODECLASS="literal">die</CODE></A> and  <ACLASS="olink"HREF="../prog/ch03_032.htm"><CODECLASS="literal">eval</CODE></A> functions in <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A> and <ICLASS="filename">perlfunc </I>(1); <ACLASS="xref"HREF="ch10_16.htm"TITLE="Trapping Undefined Function Calls with AUTOLOAD">Recipe 10.15</A>; <ACLASS="xref"HREF="ch12_03.htm"TITLE="Trapping Errors in require or use">Recipe 12.2</A>; <ACLASS="xref"HREF="ch16_22.htm"TITLE="Timing Out an Operation">Recipe 16.21</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_12.htm"TITLE="10.11. Prototyping Functions"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 10.11. Prototyping Functions"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch10_14.htm"TITLE="10.13. Saving Global Values"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 10.13. Saving Global Values"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">10.11. Prototyping Functions</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">10.13. Saving Global Values</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -