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

📄 chapter09.html

📁 java 是一个很好的网络开发环境。由于它是通过解释的方法
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source: 
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:Tjava14.rtf
Application Directory:c:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:02/04/2000
Translation Time:23:25:12
Translation Platform:Win32
Number of Output files:27
This File:Chapter09.html
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>9: Error handling  with exceptions</TITLE>
</HEAD>

<BODY  BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
  <a href="http://www.MindView.net">
  <img src="mindview-head.gif" alt="MindView Inc." BORDER = "0"></a>
  <CENTER>
    <FONT FACE="Verdana" size = "-1">
    [ <a href="README-HTML.txt">Viewing Hints</a> ]
    [ <a href="http://www.mindview.net/TIJ2/index.html">2nd Edition</a> ]
    [ <a href="http://www.mindview.net/MailingList.html">Free Newsletter</a> ] <br>
    [ <a href="http://www.mindview.net/Training.html">Seminars</a> ]
    [ <a href="http://www.mindview.net/javaCD2.html">Seminars on CD ROM</a> ]
    [ <a href="http://www.mindview.net/CPPServices/#ConsultingServices">Consulting</a> ]
    </FONT>
  <H2><FONT FACE="Verdana">
  Thinking in Java, 1st edition</FONT></H2>
  <H3><FONT FACE="Verdana">&copy;1998 by Bruce Eckel</FONT></H3>
  
    <FONT FACE="Verdana" size = "-1">
     [ <a href="Chapter08.html">Previous Chapter</a> ] 
    [ <a href="SimpleContents.html">Short TOC</a> ] 
    [ <a href="Contents.html">Table of Contents</a> ] 
    [ <a href="DocIndex.html">Index</a> ]
     [ <a href="Chapter10.html">Next Chapter</a> ] 
    </FONT>
    
  </CENTER>
  </P></DIV><A NAME="Chapter_9"></A><A NAME="_Toc375545361"></A><A NAME="_Toc407441453"></A><A NAME="_Toc408018588"></A><A NAME="Heading280"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
9: Error handling <BR>with exceptions<A NAME="OLE_LINK1"></A></H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Verdana" SIZE=4>The basic philosophy of
Java is that &#8220;badly-formed code will not be run.&#8221;</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As with C++, the ideal time to
catch the <A NAME="Index901"></A><A NAME="Index902"></A>error is at compile
time, before you even try to run the program. However, not all errors can be
detected at compile time. The rest of the problems must be handled at run-time
through some formality that allows the originator of the error to pass
appropriate information to a recipient who will know how to handle the
difficulty properly.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In C and other earlier languages,
there could be several of these formalities, and they were generally established
by convention and not as part of the programming language. Typically, you
returned a special value or set a flag, and the recipient was supposed to look
at the value or the flag and determine that something was amiss. However, as the
years passed, it was discovered that programmers who use a library tend to think
of themselves as invincible, as in, &#8220;Yes, errors might happen to others
but not in <I>my</I> code.&#8221; So, not too surprisingly, they wouldn&#8217;t
check for the error conditions (and sometimes the error conditions were too
silly to check
for</FONT><A NAME="fnB38" HREF="#fn38">[38]</A><FONT FACE="Georgia">). If
you <I>were</I> thorough enough to check for an error every time you called a
method, your code could turn into an unreadable nightmare. Because programmers
could still coax systems out of these languages they were resistant to admitting
the truth: This approach to handling errors was a major limitation to creating
large, robust, maintainable programs.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The solution is to take the casual
nature out of error handling and to enforce formality. This actually has a long
history, since implementations of <I>exception handling</I> go back to operating
systems in the 1960s and even to BASIC&#8217;s <B>on error goto</B>. But C++
exception handling was based on Ada, and Java&#8217;s is based primarily on C++
(although it looks even more like Object Pascal).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The word &#8220;exception&#8221; is
meant in the sense of &#8220;I take exception to that.&#8221; At the point where
the problem occurs you might not know what to do with it, but you do know that
you can&#8217;t just continue on merrily; you must stop and somebody, somewhere,
must figure out what to do. But you don&#8217;t have enough information in the
current context to fix the problem. So you hand the problem out to a higher
context where someone is qualified to make the proper decision (much like a
chain of command).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The other rather significant
benefit of exceptions is that they clean up error handling code. Instead of
checking for a particular error and dealing with it at multiple places in your
program, you no longer need to check at the point of the method call (since the
exception will guarantee that someone catches it). And, you need to handle the
problem in only one place, the so-called <A NAME="Index903"></A><I>exception
handler</I>. This saves you code and it separates the code that describes what
you want to do from the code that is executed when things go awry. In general,
reading, writing, and debugging code becomes much clearer with exceptions than
when using the old way.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Because exception handling is
enforced by the Java compiler, there are only so many examples that can be
written in this book without learning about exception handling. This chapter
introduces you to the code you need to write to properly handle the exceptions,
and the way you can generate your own exceptions if one of your methods gets
into
trouble.</FONT><A NAME="_Toc375545362"></A><A NAME="_Toc408018589"></A><BR></P></DIV>
<A NAME="Heading281"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Basic exceptions</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">An
<A NAME="Index904"></A><I>exceptional condition</I> is a problem that prevents
the continuation of the method or scope that you&#8217;re in. It&#8217;s
important to distinguish an exceptional condition from a normal problem, in
which you have enough information in the current context to somehow cope with
the difficulty. With an exceptional condition, you cannot continue processing
because you don&#8217;t have the information necessary to deal with the problem
<I>in the current context</I>. All you can do is jump out of the current context
and relegate that problem to a higher context. This is what happens when you
throw an exception.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">A simple example is a divide. If
you&#8217;re about to divide by zero, it&#8217;s worth checking to make sure you
don&#8217;t go ahead and perform the divide. But what does it mean that the
denominator is zero? Maybe you know, in the context of the problem you&#8217;re
trying to solve in that particular method, how to deal with a zero denominator.
But if it&#8217;s an unexpected value, you can&#8217;t deal with it and so must
throw an exception rather than continuing along that path.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">When you throw an
<A NAME="Index905"></A>exception, several things happen. First, the exception
object is created in the same way that any Java object is created: on the heap,
with <B>new</B>. Then the current path of execution (the one you couldn&#8217;t
continue, remember) is stopped and the handle for the exception object is
ejected from the current context. At this point the exception-handling mechanism
takes over and begins to look for an appropriate place to continue executing the
program. This appropriate place is the <I>exception handler</I>, whose job is to
recover from the problem so the program can either try another tack or simply
continue.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As a simple example of throwing an
exception, consider an object handle called <B>t</B>. It&#8217;s possible that
you might be passed a handle that hasn&#8217;t been initialized, so you might
want to check before trying to call a method using that object handle. You can
send information about the error into a larger context by creating an object
representing your information and &#8220;throwing&#8221; it out of your current
context. This is called <I>throwing an exception</I>. Here&#8217;s what it looks
like:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#0000ff>if</font>(t == <font color=#0000ff>null</font>)
  <font color=#0000ff>throw</font> <font color=#0000ff>new</font> NullPointerException();</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This throws the exception, which
allows you &#8211; in the current context &#8211; to abdicate responsibility for
thinking about the issue further. It&#8217;s just magically handled somewhere
else. Precisely <I>where </I>will be shown
shortly.</FONT><A NAME="_Toc375545363"></A><A NAME="_Toc408018590"></A><BR></P></DIV>
<A NAME="Heading282"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
Exception arguments<BR><A NAME="Index906"></A><A NAME="Index907"></A></H3></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Like any object in Java, you always
create exceptions on the heap using <B>new</B> and a constructor gets called.
There are two constructors in all the standard exceptions; the first is the
default constructor, and the second takes a string argument so you can place
pertinent information in the exception:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#0000ff>if</font>(t == <font color=#0000ff>null</font>)
  <font color=#0000ff>throw</font> <font color=#0000ff>new</font> NullPointerException(<font color=#004488>"t = null"</font>);</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This string can later be extracted
using various methods, as will be shown later.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The <A NAME="Index908"></A>keyword
<B>throw</B> causes a number of relatively magical things to happen. First it
executes the <B>new</B>-expression to create<B> </B>an object that isn&#8217;t
there under normal program execution, and of course, the constructor is called
for that object. Then the object is, in effect, &#8220;returned&#8221; from the
method, even though that object type isn&#8217;t normally what the method is
designed to return. A simplistic way to think about exception handling is as an
alternate return mechanism, although you get into trouble if you take that
analogy too far. You can also exit from ordinary scopes by throwing an
exception. But a value is returned, and the method or scope
exits.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Any similarity to an ordinary
return from a method ends here, because <I>where</I> you return is someplace
completely different from where you return for a normal method call. (You end up
in an appropriate exception handler that might be miles away &#8211; many levels
lower on the call stack &#8211; from where the exception was
thrown.)</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In addition, you can throw any type
of <B>Throwable</B> object that you want. Typically, you&#8217;ll throw a
different class of exception for each different type of error. The idea is to
store the information in the exception object <I>and</I> in the type of
exception object chosen, so someone in the bigger context can figure out what to
do with your exception. (Often, the only information is the type of exception
object, and nothing meaningful is stored within the exception
object.)</FONT><A NAME="_Toc305593298"></A><A NAME="_Toc305628770"></A><A NAME="_Toc312374113"></A><A NAME="_Toc375545364"></A><A NAME="_Toc408018591"></A><BR></P></DIV>
<A NAME="Heading283"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Catching an exception<BR><A NAME="Index909"></A><A NAME="Index910"></A></H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">If a method throws an exception, it
must assume that exception is caught and dealt with. One of the advantages of
Java exception handling is that it allows you to concentrate on the problem
you&#8217;re trying to solve in one place, and then deal with the errors from
that code in another place.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">To see how an exception is caught,
you must first understand the concept of a
<A NAME="Index911"></A><A NAME="Index912"></A><I>guarded region</I>, which is a
section of code that might produce exceptions, and is followed by the code to
handle those
exceptions.</FONT><A NAME="_Toc312374114"></A><A NAME="_Toc375545365"></A><A NAME="_Toc408018592"></A><BR></P></DIV>
<A NAME="Heading284"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">

⌨️ 快捷键说明

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