Next: String parsing exceptions. Up: More on exceptions. Previous: None.


Checked and unchecked exceptions

Textbook: Section 8.1

Sometimes, the Java compiler will insist that you catch a particular type of exception. These are called unchecked exceptions because Java will not insist that they be checked. The exceptions we've mentioned so far have all been unchecked.

One example of a method that throws a checked exception is Thread.sleep(), which will halt for a number of milliseconds specified as a parameter.

Thread.sleep(20); // won't compile: exception not caught
This method can throw an InterruptedException, indicating that the method wasn't able to sleep as long as requested because of some other signal it received. Java will refuse to compile any code that calls Thread.sleep() but doesn't specifically handle this exception.

So what you must do is place the code that uses Thread.sleep() within a try clause, followed by a catch clause to handle an InterruptedException.

try {
    Thread.sleep(20);
} catch(InterruptedException e) { }
Notice that here, we've told Java to do nothing when the exception occurs - essentially, we just want to ignore the exception. For this particular exception, this is frequently the best thing you can do.

(In fact, we used Clock.sleep() in Labs 2 and 4, defined in the csbsju.cs160 package. We did this instead of using the Thread class in the java.lang package because doing that instead would force us to worry about this checked exception, and we hadn't studied exceptions yet.)


Next: String parsing exceptions. Up: More on exceptions. Previous: None.