📄 jaxpsax5.html
字号:
Since the <code class="cCode">SAXParseException</code> can also wrap another exception, add the code highlighted below to use the contained exception for the stack trace:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative"> ...} catch (SAXParseException err) { System.out.println("\n** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage());<code class="cCodeBold"> // Use the contained exception, if any Exception x = spe; if (spe.getException() != null) x = spe.getException(); x.printStackTrace();</code><a name="wp64621"> </a>} catch (SAXException sxe) { // Error generated by this application // (or a parser-initialization error) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace();<a name="wp64622"> </a>} catch (Throwable t) { t.printStackTrace();} <a name="wp64623"> </a></pre></div><a name="wp64624"> </a><p class="pBody">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. In a moment, you'll learn more about errors and warnings and find out how to supply an error handler to process them. </p><a name="wp64626"> </a><h4 class="pHeading3">Handling a ParserConfigurationException</h4><a name="wp64627"> </a><p class="pBody">Finally, recall that the <code class="cCode">SAXParserFactory</code> 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><a name="wp64628"> </a><p class="pBody">Add the code highlighted below to handle such errors:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">} catch (SAXException sxe) { Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace();<code class="cCodeBold">} catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace();</code>} catch (Throwable t) { t.printStackTrace();<a name="wp64629"> </a></pre></div><a name="wp64630"> </a><p class="pBody">Admittedly, there are quite a few error handlers here. But at least now you know the kinds of exceptions that can occur. </p><hr><a name="wp64631"> </a><p class="pNote">Note: A <code class="cCode">javax.xml.parsers.FactoryConfigurationError</code> 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><hr><a name="wp64633"> </a><h4 class="pHeading3">Handling an IOException</h4><a name="wp64634"> </a><p class="pBody">Finally, while we're at it, let's add a handler for <code class="cCode">IOExceptions</code>:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">} catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace();<code class="cCodeBold">} catch (IOException ioe) { // I/O error ioe.printStackTrace();}</code>} catch (Throwable t) { ...<a name="wp67967"> </a></pre></div><a name="wp70850"> </a><p class="pBody">We'll leave the handler for <code class="cCode">Throwables</code> to catch null pointer errors, but note that at this point it is doing the same thing as the <code class="cCode">IOException</code> handler. Here, we're merely illustrating the kinds of exceptions that <span style="font-style: italic">can</span> occur, in case there are some that your application could recover from.</p><a name="wp70852"> </a><h4 class="pHeading3">Handling NonFatal Errors</h4><a name="wp70853"> </a><p class="pBody">A <span style="font-style: italic">nonfatal</span> error occurs when an XML document fails a validity constraint. If the parser finds that the document is not valid, then an error event is generated. Such errors are generated by a validating parser, given a DTD or schema, when a document has an invalid tag, or a tag is found where it is not allowed, or (in the case of a schema) if the element contains invalid data.</p><a name="wp70858"> </a><p class="pBody">You won't actually dealing with validation issues until later in this tutorial. But since we're on the subject of error handling, you'll write the error-handling code now.</p><a name="wp70836"> </a><p class="pBody">The most important principle to understand about non-fatal errors is that they are <span style="font-style: italic">ignored</span>, by default. </p><a name="wp64646"> </a><p class="pBody">But if a validation error occurs in a document, you probably don't want to continue processing it. You probably want to treat such errors as fatal. In the code you write next, you'll set up the error handler to do just that.</p><hr><a name="wp64647"> </a><p class="pNote">Note: The code for the program you'll create in this exercise is in <code class="cCode"><a href="../examples/jaxp/sax/samples/Echo07.java" target="_blank">Echo07.java</a></code>.</p><hr><a name="wp64648"> </a><p class="pBody">To take over error handling, you override the <code class="cCode">DefaultHandler</code> methods that handle fatal errors, nonfatal errors, and warnings as part of the <code class="cCode">ErrorHandler</code> interface. The SAX parser delivers a <code class="cCode">SAXParseException</code> to each of these methods, so generating an exception when an error occurs is as simple as throwing it back.</p><a name="wp64649"> </a><p class="pBody">Add the code highlighted below to override the handler for errors:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public void processingInstruction(String target, String data)throws SAXException{ ...}<a name="wp70904"> </a><code class="cCodeBold">// treat validation errors as fatalpublic void error(SAXParseException e)throws SAXParseException{ throw e;}</code><a name="wp64651"> </a></pre></div><hr><a name="wp70957"> </a><p class="pNote">Note: It can be instructive to examine the error-handling methods defined in <code class="cCode">org.xml.sax.helpers.DefaultHandler</code>. You'll see that the <code class="cCode">error()</code> and <code class="cCode">warning()</code> methods do nothing, while <code class="cCode">fatalError()</code> throws an exception. Of course, you could always override the <code class="cCode">fatalError()</code> method to throw a different exception. But if your code <span style="font-style: italic">doesn't</span> throw an exception when a fatal error occurs, then the SAX parser will -- the XML specification requires it.</p><hr><a name="wp64656"> </a><h4 class="pHeading3">Handling Warnings</h4><a name="wp64657"> </a><p class="pBody">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><a name="wp64658"> </a><p class="pBody">Add the code highlighted below to generate a message when a warning occurs:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">// treat validation errors as fatalpublic void error(SAXParseException e)throws SAXParseException{ throw e;}<a name="wp64659"> </a><code class="cCodeBold">// dump warnings toopublic void warning(SAXParseException err)throws SAXParseException{ System.out.println("** Warning" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage());}</code><a name="wp64660"> </a></pre></div><a name="wp64661"> </a><p class="pBody">Since there is no good way to generate a warning without a DTD or schema, you won't be seeing any just yet. But when one does occur, you're ready!</p> </blockquote> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"> <table width="550" summary="layout" id="SummaryNotReq1"> <tr> <td align="left" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a> </td> <td align="center" valign="center"><a accesskey="p" href="JAXPSAX4.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="JAXPSAX6.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a> </td> <td align="right" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font> </font> </td> </tr> </table> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"><p><font size="-1">All of the material in <em>The J2EE(TM) 1.4 Tutorial</em> is <a href="J2EETutorialFront2.html">copyright</a>-protected and may not be published in other workswithout express written permission from Sun Microsystems.</font> </body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -