Java Reference
In-Depth Information
and the quarters end. In this lab, you will modify the FootballGame so
that it uses the Thread.sleep() method to slow the program down.
1. Open the source code file for the program you wrote in Lab 10.1 that
simulated a football game.
2. The sleep() method in the Thread class is a static method that causes
the current thread of execution to sleep for a specified number of
milliseconds. For example, the following statement pauses the cur-
rent thread for 5 seconds:
Thread.sleep(5000);
3. Add a call the Tread.sleep() before each score change and each end
of quarter in your football game. You can specify any sleep time you
want. This will slow down your game so you can “watch” it being
played.
4. Save and compile your program. It should not compile successfully.
Why not?
5. The sleep() method throws a checked exception named Interrupted-
Exception., so you need to add a try/catch block around each call to
Thread.sleep(). Print out the stack trace in each catch block.
6. Save and compile your football program again. This time, it should
compile successfully.
7.
Run the program and watch your football game being played.
The InterruptedException will never occur in your program. The only way
to cause this exception is to have a second thread interrupt your current
thread.
Summary
Exception handling is an important aspect of Java programming because
the Java language defines checked exceptions. A checked exception is
an exception that fits under the Handle or Declare Rule, meaning that it
must be either handled by a method using a try/catch block or declared
using the throws keyword.
■■
The keywords try and catch are used to create protected code. If an
exception occurs in a try block, the corresponding catch blocks attempt
to catch the exception. If the data type of the exception does match the
catch blocks, then the exception falls through to the next method on the
call stack.
■■
Search WWH ::




Custom Search