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

📄 ch30.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<H2><A NAME="ThrowinganException"><FONT SIZE=5 COLOR=#Ff0000>Throwing an Exception</FONT></A></H2><P>One handy thing about exceptions is that you don't have to handlethem in the same method in which the exception is generated. Forexample, in Listing 30.1, the applet tries to create an <TT>URL</TT>object. If the <TT>URL</TT> creation fails, the <TT>URL</TT> constructorthrows an exception that the <TT>event()</TT> method handles inits <TT>catch</TT> block. But what if, for some reason, you don'twant to handle the exception in the same method in which you callthe <TT>URL</TT> constructor? You can simply pass the buck, soto speak, by throwing the exception on up the method hierarchy.Listing 30.2 shows one way you might do this with the <TT>MalformedURLException</TT>exception.<HR><BLOCKQUOTE><B>Listing 30.2&nbsp;&nbsp;LST30_2.TXT: Throwing an Exception.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>public boolean action(Event evt, Object arg){    try        GetURL();    catch (MalformedURLException e)    {        badURL = true;        repaint();    }        return true;}protected void GetURL() throws MalformedURLException{    String str = textField.getText();    URL url = new URL(str);    AppletContext context = getAppletContext();    context.showDocument(url);}</PRE></BLOCKQUOTE><HR><P>In this listing, the call to the <TT>URL</TT> class's constructorhas been moved to a method called <TT>GetURL()</TT>. However,<TT>GetURL()</TT> does not directly handle the <TT>MalformedURLException</TT>exception. Instead, it passes the exception back to the <TT>action()</TT>method. Java knows that <TT>GetURL()</TT> wants to pass the exception,because <TT>GetURL()</TT> adds the phrase <TT>throws MalformedURLException</TT>to its signature. Throwing the exception, however, doesn't relieveyou from handling it eventually. Notice that in Listing 30.2,the exception still gets handled in the <TT>action()</TT> method.<P>In short, you can handle an exception in two ways. The first wayis to write <TT>try</TT> and <TT>catch</TT> program blocks exactlywhere you call the function that may generate the exception. Thesecond way is to declare the method as throwing the exception,in which case you must write the <TT>try</TT> and <TT>catch</TT>program blocks in the method that calls the &quot;throwing&quot;method, as shown in Listing 30.2.<H2><A NAME="TypesofExceptions"><FONT SIZE=5 COLOR=#Ff0000>Types of Exceptions</FONT></A></H2><P>Java defines many different exception objects. Some of these youmust always handle in your code if you call a function that maythrow the exception. Others are generated by the system when somethinglike memory allocation fails, an expression tries to divide byzero, a null value is used inappropriately, and so on. You canchoose to watch for this second kind of exception or let Javadeal with them.<P>Just as with programming before exceptions existed, you shouldalways be on the lookout for places in your program where an exceptioncould be generated. These places are usually associated with userinput, which can be infamously unpredictable. However, programmers,too, have been known to make mistakes in their programs that leadto exception throwing. Some common exceptions you may want towatch out for at appropriate places in your applet are listedin Table 30.1.<BR><P><CENTER><B>Table 30.1&nbsp;&nbsp;Common Java Exceptions.</B></CENTER><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=295><I><B>Exceptions</B></I></TD><TD WIDTH=295><I><B>Description</B></I></TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>ArithmeticException</TT></TD><TD WIDTH=295>Caused by math errors such as division by zero</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>ArrayIndexOutOfBounds Exception</TT></TD><TD WIDTH=295>Caused by bad array indexes </TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>ArrayStoreException</TT></TD><TD WIDTH=295>Caused when a program tries to store the wrong type of data in an array</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>FileNotFoundException</TT></TD><TD WIDTH=295>Caused by an attempt to access a nonexistent file</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>IOException</TT></TD><TD WIDTH=295>Caused by general I/O failures, such as inability to read from a file</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>NullPointerException</TT></TD><TD WIDTH=295>Caused by referencing a null object</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>NumberFormatException</TT></TD><TD WIDTH=295>Caused when a conversion between strings and numbers fails</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>OutOfMemoryException</TT></TD><TD WIDTH=295>Caused when there's not enough memory to allocate a new object</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>SecurityException</TT></TD><TD WIDTH=295>Caused when an applet tries to perform an action not allowed by the browser's security setting</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>StackOverflowException</TT></TD><TD WIDTH=295>Caused when the system runs out of stack space</TD></TR><TR VALIGN=TOP><TD WIDTH=295><TT>StringIndexOutOfBounds Exception</TT></TD><TD WIDTH=295>Caused when a program attempts to access a nonexistent characterposition in a string </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>You can catch all types of exceptions by setting up your <TT>catch</TT> block for exceptions of type <TT>Exception</TT>, like this: <TT>catch (Exception e)</TT>. Call the exception's <TT>getMessage()</TT> method (inherited from the <TT>Throwable</TT> superclass) to get information about the specific exception that you've intercepted.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="DeterminingtheExceptionstoHandle"><FONT SIZE=5 COLOR=#Ff0000>Determining the Exceptions to Handle</FONT></A></H2><P>Experienced programmers usually know when their code may generatean exception of some sort. However, when you first start writingapplets with exception-handling code, you may not be sure whattype of exceptions to watch out for. One way to discover thisinformation is to see what exceptions get generated as you testyour applet. Listing 30.3, for example, is an applet called ExceptionAppletthat divides two integer numbers obtained from the user and displaysthe integer result (dropping any remainder). Because the appletmust deal with user input, the probability of disaster is high.ExceptionApplet, however, contains no exception-handling code.<HR><BLOCKQUOTE><B>Listing 30.3&nbsp;&nbsp;ExceptionApplet.java: An Applet withNo Exception Handling.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class ExceptionApplet extends Applet{    TextField textField1, textField2;    String answerStr;    public void init()    {        textField1 = new TextField(15);        add(textField1);        textField2 = new TextField(15);        add(textField2);        answerStr = &quot;Undefined&quot;;    }    public void paint(Graphics g)    {        Font font = new Font(&quot;TimesRoman&quot;, Font.PLAIN, 24);        g.setFont(font);int answer = int1 / int2;        answerStr = String.valueOf(answer);        repaint();        return true;    }}</PRE></BLOCKQUOTE><HR><P>You'll use this applet as the starting point for a more robustapplet. When you run the applet using Appletviewer, you'll seethe window shown in Figure 30.4. Enter a number into each of thetwo text boxes and then press Enter. The program then dividesthe first number by the second number and displays the result(see Figure 30.5).<P><A HREF="f30-4.gif"><B> Figure 30.4 : </B><I>This is ExceptionApplet running under Appletviewer.</I></A><P><P><A HREF="f30-5.gif"><B> Figure 30.5 : </B><I>ExceptionApplet divides the first number by the second.</I></A><P><P>As long as the user enters valid numbers into the text boxes,the program runs perfectly. What happens, though, if the userpresses Enter when either or both of the text boxes are empty?Java immediately throws a <TT>NumberFormatException</TT> whenthe <TT>action()</TT> method attempts to convert the contentsof the text boxes to integer values. You can see this happeningby watching the DOS window from which you ran Appletviewer, asshown in Figure 30.6. As you can see in the figure, Java has displayedquite a few lines that trace the exception. The first line (theone that starts with the word <TT>exception</TT>) tells you thetype of exception you've encountered.<P><A HREF="f30-6.gif"><B> Figure 30.6 : </B><I>Here, Java reports a NumberFormat<r>Exception exception.</I></A><P><H3><A NAME="ExampleCatchingaRuntimeException">Example: Catching a Runtime Exception</A></H3><P>You now know that the user can cause a <TT>NumberFormatException</TT>if he or she leaves one or more text boxes blank or enters aninvalid numerical value, like the string <TT>one</TT>. In orderto ensure that your applet will not be caught by surprise, younow need to write the code that will handle this exception. Followthese steps to add this new code:<OL><LI>Load ExceptionApplet into your text editor.<LI>Replace the <TT>action()</TT> method with the new versionshown in Listing 30.4.<LI>In the class declaration line, change the name of the classto <TT>ExceptionApplet2</TT>.<LI>Save the new applet under the name ExceptionApplet2.java.<LI>Load the EXCEPTIONAPPLET.htmL file.<LI>Change all occurrences of <TT>ExceptionApplet</TT> to <TT>ExceptionApplet2</TT>.<LI>Save the file as EXCEPTIONAPPLET2.htmL.</OL><HR><BLOCKQUOTE>

⌨️ 快捷键说明

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