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

📄 ch30.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<B>Listing 30.4&nbsp;&nbsp;LST30_4.TXT: Handling the </B><I>NumberFormatException</I><B>Exception.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>    public boolean action(Event evt, Object arg)    {        String str1 = textField1.getText();        String str2 = textField2.getText();        try        {            int int1 = Integer.parseInt(str1);            int int2 = Integer.parseInt(str2);            int answer = int1 / int2;            answerStr = String.valueOf(answer);        }        catch (NumberFormatException e)        {            answerStr = &quot;Bad number!&quot;;        }        repaint();        return true;    }</PRE></BLOCKQUOTE><HR><P>In Listing 30.4, the <TT>action()</TT> method now uses <TT>try</TT>and <TT>catch</TT> program blocks to handle the <TT>NumberFormatException</TT>gracefully. Figure 30.7 shows what happens now when the user leavesthe text boxes blank. When the program gets to the first callto <TT>String.valueOf()</TT>, Java generates the <TT>NumberFormatException</TT>exception, which causes program execution to jump to the <TT>catch</TT>block. In the <TT>catch</TT> block, the program sets the displaystring to <TT>Bad number!</TT> The call to <TT>repaint()</TT>ensures that this message to the user gets displayed on the screen.<P><A HREF="f30-7.gif"><B> Figure 30.7 : </B><I>ExceptionApplet2 handles the NumberFormat<r>Exception exception gracefully.</I></A><P><H3><A NAME="ExampleHandlingMultipleExceptions">Example: Handling Multiple Exceptions</A></H3><P>So, here you are, having a good time entering numbers into ExceptionApplet2'stext boxes and getting the results. Without thinking, you entera zero into the second box, Java tries to divide the first numberby the zero, and pow!- you've got yourself an <TT>ArithmeticException</TT>exception. What to do? You're already using your <TT>catch</TT>block to grab <TT>NumberFormatException</TT>; now, you've gotyet another exception to deal with.<P>The good news is that you're not limited to only a single <TT>catch</TT>block. You can, in fact, create <TT>catch</TT> blocks for anyexceptions you think the program may generate. To see how thisworks with your new applet, follow these steps:<OL><LI>Load ExceptionApplet2 into your text editor.<LI>Replace the <TT>action()</TT> method with the new versionshown in Listing 30.5.<LI>In the class declaration line, change the name of the classto <TT>ExceptionApplet3</TT>.<LI>Save the new applet under the name ExceptionApplet3.java.<LI>Load the EXCEPTIONAPPLET.htmL file.<LI>Change all occurrences of <TT>ExceptionApplet</TT> to <TT>ExceptionApplet3</TT>.<LI>Save the file as EXCEPTIONAPPLET3.htmL.</OL><HR><BLOCKQUOTE><B>Listing 30.5&nbsp;&nbsp;LST30_5.TXT: Handling Multiple Exceptions.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>    public boolean action(Event evt, Object arg)    {        String str1 = textField1.getText();        String str2 = textField2.getText();        try        {            int int1 = Integer.parseInt(str1);            int int2 = Integer.parseInt(str2);            int answer = int1 / int2;            answerStr = String.valueOf(answer);        }        catch (NumberFormatException e)        {            answerStr = &quot;Bad number!&quot;;        }        catch (ArithmeticException e)        {            answerStr = &quot;Division by 0!&quot;;        }        repaint();        return true;    }</PRE></BLOCKQUOTE><HR><P>If you examine Listing 30.5, you'll see that the <TT>action()</TT>method now defines two <TT>catch</TT> program blocks, one eachfor the <TT>&nbsp;NumberFormatException&nbsp;</TT> and <TT>&nbsp;ArithmeticException</TT>exceptions. In this way, the program can watch for both potentialproblems from within a single <TT>try</TT> block. If you discoveredanother exception that your program may cause, you can add yetanother <TT>catch</TT> block.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Although handling exceptions is a powerful tool for creating crash-proof programs, you should use them only in situations where you have little control over the cause of the exception, such as when dealing with user input. If your applet causes an exception because of a program bug, you should track down and fix the problem rather than try to catch the exception.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>There may be times when you want to be sure that a specific block of code gets executed whether or not an exception is generated. You can do this by adding a <TT>finally</TT> program block after the last <TT>catch</TT>. The code in the <TT>finally</TT> block gets executed after the <TT>try</TT> block or <TT>catch</TT> block finishes its thing.</BLOCKQUOTE></TD></TR></TABLE></CENTER><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>A good applet doesn't give the user nasty surprises. It's up tothe programmer to check for potential problem spots in programsand guard against program failure. One tool the programmer canuse is exceptions, which are objects created by Java when a programencounters a serious error. After Java creates an exception object,it throws the exception and expects some other part of the programto catch the exception.<P>The <TT>try</TT> and <TT>catch</TT> program blocks enable youto test for exceptions and respond to them as appropriate. Sometypes of exceptions must be handled in your program before theJava compiler will compile the program. Other exceptions-thosethat may be generated at runtime by more unpredictable problemslike referencing a null pointer or dividing by zero-don't haveto be handled in your program. However, a good programmer willdesign his or her applet so that common exceptions are handledwhere appropriate.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>How do you use a <TT>try</TT> program block?<LI>How do you use a <TT>catch</TT> program block?<LI>Do you have to catch all types of exceptions that might bethrown by Java?<LI>When a method you call is defined as potentially throwingan exception, do you have to handle that exception in your program?<LI>How many exceptions can you associate with a single <TT>try</TT>block?<LI>How do you pass an exception up from a called method to thecalling method?<LI>What are the two main types of exceptions that Java may throw?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an applet that creates a button object. Set up exception-handlingcode for the <TT>OutOfMemoryException</TT> exception that couldpossibly occur when Java tries to allocate resources for the button.<LI>Write an applet that catches all <TT>Exception</TT> objectsand displays the string returned by the <TT>Exception</TT> object's<TT>getMessage()</TT> method. (Not all <TT>Exception</TT> objectsreturn message strings. Test your program by generating a divide-by-zeroerror, which will cause Java to throw an <TT>ArithmeticException</TT>exception. This exception does generate a message string.) Youcan find the solution to this exercise in the CHAP30 folder ofthis book's CD-ROM. The applet is called ExceptionApplet4. Figure30.8 shows what the applet looks like while running under Appletviewer.<BR><A HREF="f30-8.gif"><B> Figure 30.8 : </B><I>ExceptionApplet4 displays the message string returned by an Exception object's getMessage() method.</I></A><P><LI>Write an applet that enables the user to enter values intoan array. Use two TextField objects, the first being where theuser shouldenter the index at which to place the value, and thesecond being the value to add to the array. Set up the appletso that it responds to <TT>ArrayIndexOutOfBoundsException</TT>and <TT>NumberFormatException</TT> exceptions. You can find thesolution to this exercise in the CHAP30 folder of this book'sCD-ROM. The applet is called ExceptionApplet5. Figure 30.9 showswhat the applet looks like while running under Appletviewer.<P><A HREF="f30-9.gif"><B> Figure 30.9 : </B><I>This is ExceptionApplet5 running under Appletviewer.</I></A><P></OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>,  All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>

⌨️ 快捷键说明

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