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

📄 3_error.html

📁 XML_JAVA指南 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 377 KB
💻 HTML
📖 第 1 页 / 共 2 页
字号:
    if (sxe.getException() != null)        x = sxe.getException();    x.printStackTrace();</STRONG></I></B>} catch (Throwable t) {    t.printStackTrace ();}</PRE></BLOCKQUOTE><P>This code tests to see if the <CODE>SAXException</CODE> is wrapping another   exception. If so, it generates a stack trace originating from where that exception   occurred to make it easier to pinpoint the code responsible for the error. If   the exception contains only a message, the code prints the stack trace starting   from the location where the exception was generated.</P><H3><A NAME=improving></A>Improving the SAXParseException Handler</H3><P>Since the <CODE>SAXParseException</CODE> can also wrap another exception, add   the code highlighted below to use it for the stack trace:</P><BLOCKQUOTE>   <PRE><NEW>  ...} catch (SAXParseException err) {     System.out.println ("** Parsing error"         + ", line " + err.getLineNumber ()        + ", uri " + err.getSystemId ());     System.out.println("   " + err.getMessage ());<B>     // Unpack the delivered exception to get the exception it contains     Exception  x = <A name=DIFF14></A><A href=#DIFF15><IMG src=../diffpics/oold.gif></A><STRIKE>err; if (err.getException () != null) x = err.getException (); x.printStackTrace (); } catch (SAXException e) { Exception x = e; </STRIKE><A name=DIFF14></A><A href=#DIFF15><IMG src=../diffpics/onew.gif></A><STRONG><I>spe;       if (spe.getException() != null)           x = spe.getException();       x.printStackTrace();</B>} catch (SAXException e) {<B>    </B>// Error generated by this application    // (or a parser-initialization error)<B></B>    Exception	x = e;    </STRONG></I>if (e.getException () != null)        x = e.getException ();    x.printStackTrace ();<B></B>} catch (Throwable t) {    t.printStackTrace ();}<B>      </B></NEW></PRE></BLOCKQUOTE>The program is now ready to handle any SAX parsing exceptions it sees. You've seen that the parser generates exceptions for fatal errors. But for nonfatal errors and warnings, exceptions are never generated by the default error handler, and no messages are displayed. Next, you'll learn more about errors and warnings and find out how to supply an error handler to process them. <H3><A name=DIFF15></A><A href=#DIFF16><IMG src=../diffpics/onew.gif></A><STRONG><I><A NAME=parserconfigerr></A>Handling a <B>ParserConfigurationException</B></H3><P>Finally, recall that the SAXParserFactory class could throw an exception if   it were for unable to create a parser. Such an error might occur if the factory   could not find the class needed to create the parser (class not found error),   was not permitted to access it (illegal access exception), or could not instantiate   it (instantiation error).</P><P>Add the code highlighted below to handle such errors:</P><BLOCKQUOTE>   <PRE>} catch (SAXException e) {    Exception	x = e;    if (e.getException () != null)        x = e.getException ();    x.printStackTrace ();<B><NEW></NEW>} catch (ParserConfigurationException pce) {    // Parser with specified options can't be built    pce.printStackTrace();</B>} catch (Throwable t) {    t.printStackTrace ();</PRE></BLOCKQUOTE><P>This code, like the SAXException handler, takes into account the possibility   that the reported exception might be wrapping another exception. (Admittedly,   there are quite a few error handlers here. But at least now you know the kinds   of exceptions that can occur.) </P><BLOCKQUOTE>   <P><B>Note: </B><BR>    A <TT>javax.xml.parsers.</TT>FactoryConfigurationError could also be thrown     if the factory class specified by the system property cannot be found or instantiated.     That is a non-trappable error, since the program is not expected to be able     to recover from it.</P></BLOCKQUOTE><H3><A NAME=ioerr></A>Handling an <B>IOException</B></H3><BLOCKQUOTE></BLOCKQUOTE><P>Finally, while we're at it, let's stop intercepting all Throwable objects and   catch the only remaining exceptions there is to catch, IOExceptions:</P><BLOCKQUOTE>   <PRE>} catch (ParserConfigurationException pce) {    // Parser with specified options can't be built    pce.printStackTrace();<B></B><S>} catch (Throwable t) {</S>    <S>t.printStackTrace ();</S><B>} catch (IOException ioe) {    // I/O error    ioe.printStackTrace();</B>}</STRONG></I></PRE></BLOCKQUOTE><H3><A NAME=understandingNonFatal></A>Understanding NonFatal Errors</H3><P>In general, a nonfatal <I>error</I> occurs when an XML document fails a validity   constraint. If the parser finds that the document is not <A HREF=../glossary.html#valid>valid</A>   (which means that it contains an invalid tag or a tag in location that is disallowed),   then an error event is generated. In general, then, errors are generated by   the <A HREF=../../api/com/sun/xml/parser/ValidatingParser.html>ValidatingParser</A>,   given a <A HREF=../glossary.html#DTD>DTD</A> that tells it which tags are   valid. There is one kind of error, though, that is generated by the nonvalidating   parser you have been working with so far. You'll experiment with that error   next. </P><BLOCKQUOTE>   <P><B>Note:</B> The file you'll create in this exercise is <A HREF=samples/slideSampleBad2.xml><CODE>slideSampleBad2.xml</CODE></A>.     The output is in <A HREF=work/Echo06-Bad2.log><CODE>Echo06-Bad2.log</CODE></A>.   </P></BLOCKQUOTE><P>The SAX specification requires an error event to be generated if the XML document   uses a version of XML that the parser does not support. To generate such an   error, make the changes shown below to alter your XML file so it specifies <CODE>version=&quot;1.2&quot;</CODE>.</P><BLOCKQUOTE>   <PRE>&lt;?xml version='1.<S>0</S><B>2</B>' encoding='us-ascii'?&gt;</PRE></BLOCKQUOTE><P>Now run your version of the Echo program on that file. What happens? (See below   for the answer.)</P><BLOCKQUOTE>   <P><B>Answer: </B>Nothing happens! By default, the error is ignored. The output     from the Echo program looks the same as if <CODE>version=&quot;1.0&quot;<A name=DIFF16></A><A href=#DIFF17><IMG src=../diffpics/oold.gif></A><STRIKE>had beenproperly specified. </STRIKE><A name=DIFF16></A><A href=#DIFF17><IMG src=../diffpics/onew.gif></A><STRONG><I></CODE>     had been properly specified. </STRONG></I>To do something else, you need to supply your     own error handler. You'll do that next.</P></BLOCKQUOTE><H3><A NAME=handlingNonFatal></A>Handling Nonfatal Errors</H3><P>A standard treatment for &quot;nonfatal&quot; errors is to treat them as if   they were fatal. After all, if a validation error occurs in a document you are   processing, you probably don't want to continue processing it. In this exercise,   you'll do exactly that.</P><BLOCKQUOTE>   <P><B>Note:</B> The code for the program you'll create in this exercise is in     <A HREF=work/Echo07.java><CODE>Echo07.java</CODE></A>. The output is in     <A HREF=work/Echo07-Bad2.log><CODE>Echo07-Bad2.log</CODE></A>. </P></BLOCKQUOTE><P><A name=DIFF17></A><A href=#DIFF18><IMG src=../diffpics/oold.gif></A><STRIKE>To take over error handling, you supply the SAX parser with an ErrorHandler , which defines methods for handling fatal errors, nonfatal errors, and warnings. Add the code highlighted below to your Echo application to define an inner class for an error handler: ... System.exit (0); } static class MyErrorHandler extends HandlerBase { public void error (SAXParseException e) throws SAXParseException { throw e; } } static private Writer out; ... Once again, the class extends HandlerBase , which provides default implementations for the three error-event handlers that the ErrorHandler interface calls for. </STRIKE><A name=DIFF17></A><A href=#DIFF18><IMG src=../diffpics/onew.gif></A><STRONG><I>To take over error handling, you override the HandlerBase methods that handle   fatal errors, nonfatal errors, and warnings as part of the <CODE>ErrorHandler</CODE>   interface. </STRONG></I>The SAX parser delivers a <CODE>SAXParseException</CODE> to each   of these methods, so generating an exception when an error occurs is as simple   as throwing it back.</P><P><A name=DIFF18></A><A href=#DIFF19><IMG src=../diffpics/oold.gif></A><STRIKE>Next, add the code highlighted below to set up the parser so it uses an instance of your new error handler: </STRIKE><A name=DIFF18></A><A href=#DIFF19><IMG src=../diffpics/onew.gif></A><STRONG><I>Add the code highlighted below to override the handlers for errors:</STRONG></I></P><BLOCKQUOTE>   <PRE><A name=DIFF19></A><A href=#DIFF20><IMG src=../diffpics/oold.gif></A><STRIKE>// Get an instance of the non-validating parser. Parser parser; parser = ParserFactory.makeParser ("com.sun.xml.parser.Parser"); parser.setDocumentHandler ( new Echo() ); </STRIKE><A name=DIFF19></A><A href=#DIFF20><IMG src=../diffpics/onew.gif></A><STRONG><I>public void processingInstruction (String target, String data)throws SAXException{  nl();  emit ("PROCESS: ");  emit ("&lt;?"+target+" "+data+"?&gt;");}</STRONG></I><NEW><A name=DIFF20></A><A href=#DIFF21><IMG src=../diffpics/oold.gif></A><STRIKE>// Set the new error handler parser.setErrorHandler ( new MyErrorHandler () ); </STRIKE><A name=DIFF20></A><A href=#DIFF21><IMG src=../diffpics/onew.gif></A><STRONG><I><B>// treat validation errors as fatal</B></STRONG></I></NEW><A name=DIFF21></A><A href=#DIFF22><IMG src=../diffpics/oold.gif></A><STRIKE>// Parse the input parser.parse (input); </STRIKE><NEW><A name=DIFF22></A><A href=#DIFF23><IMG src=../diffpics/onew.gif></A><STRONG><I><B>public void error (SAXParseException e)</B></NEW><NEW><B>throws SAXParseException</B></NEW><NEW><B>{</B></NEW>  <NEW><B>throw e;</B></NEW><NEW><B>}</B></STRONG></I></NEW><NEW></NEW></PRE></BLOCKQUOTE><P>Now when you run your app on the file with the faulty version number, you get   an exception, as shown here (but slightly reformatted for readability):</P><BLOCKQUOTE>   <PRE>START DOCUMENT&lt;?xml version='1.0' encoding='UTF-8'?&gt;<BR>   <B>** Parsing error, line 1, uri file:/<I>&lt;path&gt;</I>/slideSampleBad2.xml   XML version "1.0" is recognized, but not "1.2".org.xml.sax.SAXParseException: XML version "1.0" is recognized, but not "1.2".<A name=DIFF23></A><A href=#DIFF24><IMG src=../diffpics/oold.gif></A><STRIKE>at com.sun.xml.parser.Parser.error(Parser.java:2775) at com.sun.xml.parser.Parser.readVersion(Parser.java:1051) at com.sun.xml.parser.Parser.maybeXmlDecl(Parser.java:983) at com.sun.xml.parser.Parser.parseInternal(Parser.java:477) at com.sun.xml.parser.Parser.parse(Parser.java:283) at Echo.main(Echo.java:76) </STRIKE><A name=DIFF23></A><A href=#DIFF24><IMG src=../diffpics/onew.gif></A><STRONG><I></B>at com.sun.xml.parser.Parser.error(Parser.java:2778)at com.sun.xml.parser.Parser.readVersion(Parser.java:1052)at com.sun.xml.parser.Parser.maybeXmlDecl(Parser.java:984)at com.sun.xml.parser.Parser.parseInternal(Parser.java:478)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 Echo07.main(Echo07.java:59) </STRONG></I></PRE>  <P><B>Note: <A name=DIFF24></A><A href=#DIFF25><IMG src=../diffpics/oold.gif></A><STRIKE>The error actually occurs after the startDocument event has been generated, so the document header that the program &quot;echoes&quot; </STRIKE><A name=DIFF24></A><A href=#DIFF25><IMG src=../diffpics/onew.gif></A><STRONG><I></B>The error actually occurs after the <CODE>startDocument</CODE>     event has been generated. The document header that the program &quot;echoes&quot;     </STRONG></I>is the one it <A name=DIFF25></A><A href=#DIFF26><IMG src=../diffpics/oold.gif></A><STRIKE>expects, </STRIKE><A name=DIFF25></A><A href=#DIFF26><IMG src=../diffpics/onew.gif></A><STRONG><I>creates on the assumption that everything is ok, </STRONG></I>rather than     the one that is actually in the file. </P></BLOCKQUOTE><H3> <A NAME=warnings></A>Handling Warnings</H3><P>Warnings, too, are ignored by default. Warnings are informative, and require   a DTD. For example, if an element is defined twice in a DTD, a warning is generated   -- it's not illegal, and it doesn't cause problems, but it's something you might   like to know about since it might not have been intentional.</P><P>Add the code highlighted below to generate a message when a warning occurs:</P><BLOCKQUOTE>   <PRE><NEW><A name=DIFF26></A><A href=#DIFF27><IMG src=../diffpics/oold.gif></A><STRIKE>static class MyErrorHandler extends HandlerBase { public void error (SAXParseException e) throws SAXParseException { throw e; } public void warning (SAXParseException err) throws SAXParseException { System.out.println ("** Warning" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ()); </STRIKE></NEW><NEW><A name=DIFF27></A><A href=#DIFF28><IMG src=../diffpics/onew.gif></A><STRONG><I>// treat validation errors as fatal</NEW><NEW>public void error (SAXParseException e)</NEW><NEW>throws SAXParseException</NEW><NEW>{</NEW>  <NEW>throw e;</NEW><NEW>}</NEW><NEW><B>// dump warnings too</B></NEW><NEW><B>public void warning (SAXParseException err)</B></NEW><NEW><B>throws SAXParseException</B></NEW><NEW><B>{</B></NEW>  <NEW><B>System.out.println ("** Warning"</B></NEW>      <NEW><B>+ ", line " + err.getLineNumber ()</B></NEW>      <NEW><B>+ ", uri " + err.getSystemId ());</STRONG></I></B></NEW>  <NEW><B>System.out.println("   " + err.getMessage ());<A name=DIFF28></A><A href=#DIFF29><IMG src=../diffpics/oold.gif></A><STRIKE>} } </STRIKE></B></NEW><NEW><A name=DIFF29></A><A href=#DIFF30><IMG src=../diffpics/onew.gif></A><STRONG><I><B>}</B></STRONG></I></NEW></PRE></BLOCKQUOTE><P>Since there is no good way to generate a warning without a DTD, you won't be   seeing any just yet. But when one does occur, you're ready!</P><BLOCKQUOTE>   <P><B>Note: </B>By default, <CODE>HandlerBase</CODE> throws an exception when     a fatal error occurs. You could override the <CODE>fatalError</CODE> method     to throw a different exception, if you like. But if your code doesn't, the     <A name=DIFF30></A><A href=#DIFF0><IMG src=../diffpics/oold.gif></A><STRIKE>Java XML </STRIKE><A name=DIFF30></A><A href=#DIFF0><IMG src=../diffpics/onew.gif></A><STRONG><I>reference implementation's </STRONG></I>SAX parser will.</P>  <HR SIZE=4></BLOCKQUOTE><P> <P> <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></BODY></HTML>

⌨️ 快捷键说明

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