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

📄 3_error.html

📁 XML_JAVA指南 书籍语言: 简体中文 书籍类型: 程序设计 授权方式: 免费软件 书籍大小: 377 KB
💻 HTML
📖 第 1 页 / 共 2 页
字号:
    Exception  x = sxe;
    if (sxe.getException() != null)
        x = sxe.getException();
    x.printStackTrace();

</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 = 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;
    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="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>
}</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/internal/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;</code> 
    had been properly specified. 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>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. 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>Add the code highlighted below to override the handlers for errors:</p>
<blockquote> 
  <pre>public void processingInstruction (String target, String data)
throws SAXException
{
  nl();
  emit ("PROCESS: ");
  emit ("&lt;?"+target+" "+data+"?&gt;");
}

<new><b>// treat validation errors as fatal</b></new>
<new><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></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".
</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) </pre>
  <p><b>Note: </b>The error actually occurs after the <code>startDocument</code> 
    event has been generated. The document header that the program &quot;echoes&quot; 
    is the one it creates on the assumption that everything is ok, 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></new><new>// 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 ());</b></new>
  <new><b>System.out.println("   " + err.getMessage ());</b></new>
<new><b>}</b></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 
    reference implementation's 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 + -