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

📄 3_error.html

📁 XML_JAVA指南 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 377 KB
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><TITLE>Handling Errors with the Non-Validating Parser</TITLE><STYLE TYPE=text/css></STYLE></HEAD><BODY BGCOLOR=#ffffff><HR><B>HtmlDiff: </B>Here is the <A href=#DIFF0>first difference.</A> There are 31 differences. <IMG src=../diffpics/oold.gif><STRIKE>is old.</STRIKE><IMG src=../diffpics/onew.gif><STRONG><I> is new. </I></STRONG><HR><TABLE WIDTH=100%><TR>    <TD ALIGN=left> <A HREF=2b_echo.html><IMG SRC=../images/PreviousArrow.gif WIDTH=26 HEIGHT=26 ALIGN=bottom BORDER=0 ALT="Previous | "></A><A HREF=4_refs.html><IMG SRC=../images/NextArrow.gif WIDTH=26 HEIGHT=26 ALIGN=bottom BORDER=0 ALT="Next | "></A><A HREF=../alphaIndex.html><IMG SRC=../images/xml_IDX.gif WIDTH=26 HEIGHT=26 ALIGN=bottom BORDER=0 ALT="Index | "></A><A HREF=../TOC.html><IMG SRC=../images/xml_TOC.gif WIDTH=26 HEIGHT=26 ALIGN=bottom BORDER=0 ALT="TOC | "></A><A HREF=../index.html><IMG SRC=../images/xml_Top.gif WIDTH=26 HEIGHT=26 ALIGN=bottom BORDER=0 ALT="Top | "></A>     </TD><TD ALIGN=right><STRONG><EM><A HREF=index.html>Top</A></EM></STRONG> <A HREF=../TOC.html#intro><STRONG><EM>Contents</EM></STRONG></A> <A HREF=../alphaIndex.html><STRONG><EM>Index</EM></STRONG></A> <A HREF=../glossary.html><STRONG><EM>Glossary</EM></STRONG></A></TD></TR></TABLE><P><CENTER>    <IMG SRC=../images/shoeline2.gif ALIGN=BOTTOM BORDER=0 WIDTH=202 HEIGHT=25 NATURALSIZEFLAG=3> <IMG SRC=../images/shoeline2.gif ALIGN=BOTTOM BORDER=0 WIDTH=202 HEIGHT=25 NATURALSIZEFLAG=3>   </CENTER>  <BLOCKQUOTE>      <BLOCKQUOTE>         <HR SIZE=4>     </BLOCKQUOTE>  </BLOCKQUOTE><H2><A name=DIFF0></A><A href=#DIFF1><IMG src=../diffpics/onew.gif></A><STRONG><I>3. </STRONG></I>Handling Errors with the Nonvalidating Parser</H2><TABLE WIDTH=40% BORDER=1 ALIGN=right>  <TR>     <TD>       <DIV ALIGN=center><B><I>Link Summary</I></B></DIV>    </TD>  </TR>  <TR>     <TD>       <DL>         <DT><B><I>Exercises</I></B></DT>      </DL>      <UL>        <LI><A HREF=samples/slideSampleBad1.xml>slideSampleBad1.xml</A> </LI>        <LI><A HREF=work/Echo05-Bad1.log>Echo05-Bad1.log</A></LI>        <LI><A HREF=work/Echo06.java>Echo06.java</A></LI>        <LI><A HREF=work/Echo06-Bad1.log>Echo06-Bad1.log</A></LI>        <LI><A HREF=samples/slideSampleBad2.xml>slideSampleBad2.xml</A></LI>        <LI><A HREF=work/Echo06-Bad2.log>Echo06-Bad2.log</A></LI>        <LI><A HREF=work/Echo07.java>Echo07.java</A></LI>        <LI><A HREF=work/Echo07-Bad2.log>Echo07-Bad2.log</A></LI>      </UL>      <P><B><I>API Links</I></B></P>      <UL>        <LI><A HREF=../../api/org/xml/sax/DocumentHandler.html>DocumentHandler</A></LI>        <LI><A HREF=../../api/com/sun/xml/parser/ValidatingParser.html>ValidatingParser</A></LI>        <LI><A HREF=../../api/org/xml/sax/ErrorHandler.html>ErrorHandler</A></LI>        <LI><A HREF=../../api/org/xml/sax/HandlerBase.html>HandlerBase</A></LI>      </UL>      <P><B><I>Glossary Terms</I></B></P>      <DL>         <DD><A HREF=../glossary.html#DTD>DTD</A>, <A HREF=../glossary.html#error>error</A>,           <A HREF=../glossary.html#fatalError>fatal error</A>, <A HREF=../glossary.html#valid>valid</A>,           <A HREF=../glossary.html#warning>warning</A>, <A HREF=../glossary.html#wellFormed>well-formed</A>         </DD>      </DL>    </TD>  </TR></TABLE><P>This version of the Echo program uses the nonvalidating parser. So it can't   tell if the XML document contains the right tags, or if those tags are in the   right sequence. In other words, it can't tell you if the document is <A HREF=../glossary.html#valid>valid</A>.   It can, however, tell whether or not the document is <A HREF=../glossary.html#wellFormed>well-formed</A>. <P> In this section of the tutorial, you'll modify the slideshow file to generate   different kinds of errors and see how the parser handles them. You'll also find   out which error conditions are ignored, by default, and see how to handle them. <H3><A NAME=introducing></A>Introducing an Error</H3><P>The parser can generate one of three kinds of errors: <A HREF=../glossary.html#fatalError>fatal   error</A>, <A HREF=../glossary.html#error>error</A>, and <A HREF=../glossary.html#warning>warning</A>.   In this exercise, you'll make a simple modification to the XML file to introduce   a fatal error. Then you'll see how it's handled in the Echo app.</P><BLOCKQUOTE>   <P><B>Note:</B> The XML structure you'll create in this exercise is in <A HREF=samples/slideSampleBad1.xml><CODE>slideSampleBad1.xml</CODE></A>.     The output is in <A HREF=work/Echo05-Bad1.log><CODE>Echo05-Bad1.log</CODE></A>.</P></BLOCKQUOTE><P> One easy way to introduce a fatal error is to remove the final &quot;<CODE>/</CODE>&quot;   from the empty <CODE><A name=DIFF1></A><A href=#DIFF2><IMG src=../diffpics/oold.gif></A><STRIKE>slide </STRIKE><A name=DIFF1></A><A href=#DIFF2><IMG src=../diffpics/onew.gif></A><STRONG><I>item</STRONG></I></CODE> element to create a tag that does not have   a corresponding end tag. That constitutes a fatal error, because all XML documents   must, by definition, be well formed. Do the following:</P><OL>  <LI>     <P>Copy <CODE>slideSample.xml</CODE> to <CODE>badSample.xml</CODE>.</P>  </LI>  <LI>Edit <CODE>badSample.xml</CODE> and remove the character <A name=DIFF2></A><A href=#DIFF3><IMG src=../diffpics/oold.gif></A><STRIKE>highlighted </STRIKE><A name=DIFF2></A><A href=#DIFF3><IMG src=../diffpics/onew.gif></A><STRONG><I>shown </STRONG></I>below:</LI>  <PRE> ...&lt;!-- OVERVIEW --&gt;&lt;slide type="all"&gt;  &lt;title&gt;Overview&lt;/title&gt;  &lt;item&gt;Why &lt;em&gt;WonderWidgets&lt;/em&gt; are great&lt;/item&gt;  &lt;item<B><S>/</S></B>&gt;  &lt;item&gt;Who &lt;em&gt;buys&lt;/em&gt; WonderWidgets&lt;/item&gt;&lt;/slide&gt; ...</PRE>  <P>to produce:</P>  <PRE> ...&lt;item&gt;Why &lt;em&gt;WonderWidgets&lt;/em&gt; are great&lt;/item&gt;&lt;item<B></B>&gt;&lt;item&gt;Who &lt;em&gt;buys&lt;/em&gt; WonderWidgets&lt;/item&gt;    ...</PRE>  <LI>Run the Echo program on the new file. <BR></OL><P>The output you get now looks like this:</P><BLOCKQUOTE>   <PRE>...        ELEMENT: &lt;item&gt;        CHARS:   The             ELEMENT: &lt;em&gt;            CHARS:   Only            END_ELM: &lt;/em&gt;        CHARS:    Section        END_ELM: &lt;/item&gt;    CHARS:       END_ELM: CHARS:   <B>org.xml.sax.SAXParseException: <A name=DIFF3></A><A href=#DIFF4><IMG src=../diffpics/oold.gif></A><STRIKE>Next character must be "&gt;" terminating element "slide". at com.sun.xml.parser.Parser.fatal(Parser.java:2797) at com.sun.xml.parser.Parser.fatal(Parser.java:2791) at com.sun.xml.parser.Parser.nextChar(Parser.java:2715) at com.sun.xml.parser.Parser.maybeElement(Parser.java:1410) at com.sun.xml.parser.Parser.content(Parser.java:1498) at com.sun.xml.parser.Parser.maybeElement(Parser.java:1399) at com.sun.xml.parser.Parser.parseInternal(Parser.java:491) at com.sun.xml.parser.Parser.parse(Parser.java:283) at Echo05.main(Echo05.java:73) </STRIKE><A name=DIFF3></A><A href=#DIFF4><IMG src=../diffpics/onew.gif></A><STRONG><I>Expected "&lt;/item&gt;"          to terminate element starting on line 20.</B>at com.sun.xml.parser.Parser.fatal(Parser.java:2800)at com.sun.xml.parser.Parser.fatal(Parser.java:2794)at com.sun.xml.parser.Parser.maybeElement(Parser.java:1406)at com.sun.xml.parser.Parser.content(Parser.java:1499)at com.sun.xml.parser.Parser.maybeElement(Parser.java:1400)at com.sun.xml.parser.Parser.content(Parser.java:1499)at com.sun.xml.parser.Parser.maybeElement(Parser.java:1400)at com.sun.xml.parser.Parser.parseInternal(Parser.java:492)at com.sun.xml.parser.Parser.parse(Parser.java:284)at javax.xml.parsers.SAXParser.parse(SAXParser.java:168)at javax.xml.parsers.SAXParser.parse(SAXParser.java:104)at javax.xml.parsers.SAXParser.parse(SAXParser.java:131)at Echo05.main(Echo05.java:59)</STRONG></I></PRE><A name=DIFF4></A><A href=#DIFF5><IMG src=../diffpics/oold.gif></A><STRIKE>&lt;BUG&gt; The diagnostic message should indicate that a terminator was not found for the item element. If it identifies any character at all, it should be looking for &quot;&lt;&quot;, rather than &quot;&gt;&quot;. This error should be fixed shortly. &lt;/BUG&gt; </STRIKE></BLOCKQUOTE><P>When a fatal error occurs, the parser is unable to continue. So, if the application   does not generate an exception (which you'll see how to do a moment), then the   default error-event handler generates one. The stack trace is generated by the   <CODE>Throwable</CODE> exception handler in your main method:</P><BLOCKQUOTE>   <PRE>  ...} catch (Throwable t) {    <B>t.printStackTrace ();</B>}</PRE></BLOCKQUOTE><P>That stack trace is not too useful, though. Next, you'll see how to generate   better diagnostics when an error occurs.</P><H3><A NAME=SAXParseException></A>Handling a SAXParseException</H3><P>When the error was encountered, the parser generated a <CODE>SAXParseException</CODE>   -- a subclass of <CODE>SAXException</CODE> that identifies the file and location   where the error occurred. </P><BLOCKQUOTE>   <P><B>Note:</B> The code you'll create in this exercise is in <A HREF=work/Echo06.java><CODE>Echo06.java</CODE></A>.     The output is in <A HREF=work/Echo06-Bad1.log><CODE>Echo06-Bad1.log</CODE></A>.</P></BLOCKQUOTE><P>Add the code highlighted below to generate a better diagnostic message when   the exception occurs: </P><BLOCKQUOTE>   <PRE><B>  ...} catch (SAXParseException <A name=DIFF5></A><A href=#DIFF6><IMG src=../diffpics/oold.gif></A><STRIKE>err) </STRIKE><A name=DIFF5></A><A href=#DIFF6><IMG src=../diffpics/onew.gif></A><STRONG><I>spe) </STRONG></I>{   <A name=DIFF6></A><A href=#DIFF7><IMG src=../diffpics/onew.gif></A><STRONG><I>// Error generated by the parser   </STRONG></I>System.out.println <A name=DIFF7></A><A href=#DIFF8><IMG src=../diffpics/oold.gif></A><STRIKE>("** </STRIKE><A name=DIFF7></A><A href=#DIFF8><IMG src=../diffpics/onew.gif></A><STRONG><I>("\n** </STRONG></I>Parsing error"       + ", line " + <A name=DIFF8></A><A href=#DIFF9><IMG src=../diffpics/oold.gif></A><STRIKE>err.getLineNumber </STRIKE><A name=DIFF8></A><A href=#DIFF9><IMG src=../diffpics/onew.gif></A><STRONG><I>spe.getLineNumber </STRONG></I>()      + ", uri " + <A name=DIFF9></A><A href=#DIFF10><IMG src=../diffpics/oold.gif></A><STRIKE>err.getSystemId </STRIKE><A name=DIFF9></A><A href=#DIFF10><IMG src=../diffpics/onew.gif></A><STRONG><I>spe.getSystemId </STRONG></I>());   <A name=DIFF10></A><A href=#DIFF11><IMG src=../diffpics/oold.gif></A><STRIKE>System.out.println(" " + err.getMessage ()); </STRIKE><A name=DIFF10></A><A href=#DIFF11><IMG src=../diffpics/onew.gif></A><STRONG><I>System.out.println("   " + spe.getMessage() );</STRONG></I></B>} catch (Throwable t) {    t.printStackTrace ();}</PRE></BLOCKQUOTE><P>Running the program now generates an error message which is a bit more helpful,   like this:</P><BLOCKQUOTE>   <PRE>** Parsing error, line <A name=DIFF11></A><A href=#DIFF12><IMG src=../diffpics/oold.gif></A><STRIKE>18, </STRIKE><A name=DIFF11></A><A href=#DIFF12><IMG src=../diffpics/onew.gif></A><STRONG><I>22, </STRONG></I>uri file:<I>&lt;path&gt;</I>/slideSampleBad1.xml   Next character must be...</PRE>  <A name=DIFF12></A><A href=#DIFF13><IMG src=../diffpics/onew.gif></A><STRONG><I><B>Note:<BR>  </B>Catching all throwables like this is <I>not</I> a good idea for production   applications.<B> </B>We're just doing it now so we can build up to full error   handling gradually.</STRONG></I><B><BR>  </B></BLOCKQUOTE><H3><A NAME=SAXException></A>Handling a SAXException</H3><P>A more general <CODE>SAXException</CODE> instance may sometimes be generated   by the parser, but it more frequently occurs when an error originates in one   of application's event handling methods. For example, the signature of the <CODE>startDocument</CODE>   method in the <A HREF=../../api/org/xml/sax/DocumentHandler.html><CODE>DocumentHandler</CODE></A>   interface is defined as returning a <CODE>SAXException</CODE>: </P><BLOCKQUOTE>   <PRE>public void startDocument () <B>throws SAXException</B></PRE></BLOCKQUOTE><P>All of the <CODE>DocumentHandler</CODE> methods (except for <CODE>setDocumentLocator</CODE>)   have that signature declaration.</P><P>A <CODE>SAXException</CODE> can be constructed using a message, another exception,   or both. So, for example, when <CODE>Echo.startDocument</CODE> outputs a string   using the <CODE>emit</CODE> method, any I/O exception that occurs is wrapped   in a <CODE>SAXException</CODE> and sent back to the parser:</P><BLOCKQUOTE>   <PRE>private void emit (String s)<B>throws SAXException</B>{    try {        out.write (s);        out.flush ();    } <B>catch (IOException e)</B> {       <B> throw new SAXException ("I/O error", e);</B>    }}</PRE>  <P><B>Note: </B>If you saved the <CODE>Locator</CODE> object when <CODE>setDocumentLocator</CODE>     was invoked, you could use it to generate a <CODE>SAXParseException</CODE>,     identifying the document and location, instead of generating a <CODE>SAXException</CODE>.</P></BLOCKQUOTE><P>When the parser delivers the exception back to the code that invoked the parser,   it makes sense to use the original exception to generate the stack trace. Add   the code highlighted below to do that:</P><BLOCKQUOTE>   <PRE> ...} catch (SAXParseException err) {    System.out.println ("** Parsing error"         + ", line " + err.getLineNumber ()        + ", uri " + err.getSystemId ());    System.out.println("   " + err.getMessage ());<A name=DIFF13></A><A href=#DIFF14><IMG src=../diffpics/oold.gif></A><STRIKE>} catch (SAXException e) { Exception x = e; if (e.getException () != null) x = e.getException (); x.printStackTrace (); </STRIKE><A name=DIFF13></A><A href=#DIFF14><IMG src=../diffpics/onew.gif></A><STRONG><I><B>} catch (SAXException sxe) {    // Error generated by this application    // (or a parser-initialization error)    Exception  x = sxe;

⌨️ 快捷键说明

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