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

📄 chap10.htm

📁 java书籍《thinking in java》
💻 HTM
📖 第 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:TIJ2.rtf
Application Directory:C:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:05/21/2001
Translation Time:10:39:17
Translation Platform:Win32
Number of Output files:23
This File:Chap10.htm
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>10: Error Handling  with Exceptions</TITLE>
</HEAD>

<BODY  BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
  <a href="http://www.MindView.net">
  <img src="mindview.gif" alt="MindView Inc." BORDER = "0"></a>
  <CENTER>
    <FONT FACE="Verdana" size = "-1">
    [ <a href="README.txt">Viewing Hints</a> ]
    [ <a href="RevHist.htm">Revision History</a> ]
    [ <a href="http://www.mindview.net/Books/TIJ/">Book Home Page</a> ]
    [ <a href="http://www.mindview.net/Etc/MailingList.html">Free Newsletter</a> ] <br>
    [ <a href="http://www.mindview.net/Seminars">Seminars</a> ]
    [ <a href="http://www.mindview.net/CDs">Seminars on CD ROM</a> ]
    [ <a href="http://www.mindview.net/Services">Consulting</a> ]
    </FONT>
  <H2><FONT FACE="Verdana">
  Thinking in Java, 2nd edition, Revision 12</FONT></H2>
  <H3><FONT FACE="Verdana">&copy;2000 by Bruce Eckel</FONT></H3>
  
    <FONT FACE="Verdana" size = "-1">
     [ <a href="Chap09.htm">Previous Chapter</a> ] 
    [ <a href="SimpCont.htm">Short TOC</a> ] 
    [ <a href="Contents.htm">Table of Contents</a> ] 
    [ <a href="DocIdx.htm">Index</a> ]
     [ <a href="Chap11.htm">Next Chapter</a> ] 
    </FONT>
    
  </CENTER>
  </P></DIV><A NAME="Chapter_9"></A><A NAME="_Toc375545361"></A><A NAME="_Toc477690730"></A><A NAME="_Toc481064713"></A><A NAME="Heading331"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
10: Error Handling <BR>with Exceptions<A NAME="OLE_LINK1"></A></H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia" SIZE=4><backtalk:display ID=TIJ3_CHAPTER10_I0>
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">The ideal time to catch an
<A NAME="Index1049"></A><A NAME="Index1050"></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.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I0' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I1>
</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&#8212;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="fnB51" HREF="#fn51">[51]</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.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I1' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I2>
</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 &#8220;<B>on error
goto</B>.&#8221; 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).

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I2' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I3>
</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). 
</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I3' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I4>
</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="Index1051"></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 of error handling.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I4' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I5>
</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 exceptions, and the way you can
generate your own exceptions if one of your methods gets into trouble.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I5' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I6>
</FONT><A NAME="_Toc375545362"></A><A NAME="_Toc481064714"></A><BR></P></DIV>
<A NAME="Heading332"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Basic exceptions</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">An <A NAME="Index1052"></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.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I6' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I7>
</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.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I7' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I8>
</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">When you throw an
<A NAME="Index1053"></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) is stopped and the reference 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 just continue.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I8' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I9>
</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As a simple example of throwing an
exception, consider an object reference called <B>t</B>. It&#8217;s possible
that you might be passed a reference that hasn&#8217;t been initialized, so you
might want to check before trying to call a method using that object reference.
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&#8212;in the current context&#8212;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.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I9' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I10>
</FONT><A NAME="_Toc375545363"></A><A NAME="_Toc481064715"></A><BR></P></DIV>
<A NAME="Heading333"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
Exception arguments<BR><A NAME="Index1054"></A><A NAME="Index1055"></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>, which allocates storage and
calls a constructor. There are two constructors in all 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 you&#8217;ll see.

</backtalk:display>
[&nbsp;<a href='http://www.mindview.net/backtalk/CommentServlet?ID=TIJ3_CHAPTER10_I10' 
  target="_blank">Add&nbsp;Comment</a>&nbsp;]

<backtalk:display ID=TIJ3_CHAPTER10_I11>
</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The <A NAME="Index1056"></A>keyword
<B>throw</B> causes a number of relatively magical things to happen. Typically,

⌨️ 快捷键说明

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