next up previous
Next: Lab Exercise 6: Adding Up: In the Laboratory: CyberPetApplet Previous: Lab Exercise 4: Tracing

Lab Exercise 5: Paying Attention to Runtime Errors

Make each of the following changes, one at a time, to your program and then rerun it. Make a note of the semantic errors that occur and try to explain each error.

This last semantic  error is a very subtle one and is worth additional comment. Consider the example in Fig 1. The semantic error in this case is a scoping error. There are two variables with the same identifier. The first is the instance variable, whose scope  extends throughout the class. It has class scope . The second is the local variable declared within the init() method, the scope of which is limited to that method. Once the init() completes its execution, the local variable ceases to exist. Outside of the init() method, any references to b1 will refer to the instance variable. The problem here is that the instance variable was never instantiated. So there is no actual button associated with its name. In the actionPerformed() method, the reference to b1 is a reference to the instance variable, but there is no button on the applet that corresponds to this variable, because in the init() method, the local  variable's button was added to the applet.



Debugging Tip: Scope Error. Don't declare a component variable in the init() method. You won't be able to refer to it in the rest of the program.



  
Figure 1: A subtle semantic error occurs in this program because the instance Button b1 is never instantiated.
\begin{figure}
\rule{4.75in}{.05cm}
\scriptsize
\begin{verbatim}
import java.awt...
 ...ed()
} // SemanticError\end{verbatim}\normalsize\rule{4.75in}{.05cm}\end{figure}


next up previous
Next: Lab Exercise 6: Adding Up: In the Laboratory: CyberPetApplet Previous: Lab Exercise 4: Tracing
Ralph Morelli {Faculty}
12/22/1999