A browser with JavaScript enabled is required for this page to operate properly.
Documentation

The Java™ Tutorials
Trail: Essential Java Classes
Lesson: Exceptions
« PreviousTrailNext »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
See Dev.java for updated tutorials taking advantage of the latest releases.
See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Questions and Exercises

Questions

  1. Is the following code legal?
    try {
     
    } finally {
     
    }
    
  2. What exception types can be caught by the following handler?
    catch (Exception e) {
     
    }
    
    What is wrong with using this type of exception handler?
  3. Is there anything wrong with the following exception handler as written? Will this code compile?
    try {
    } catch (Exception e) {
     
    } catch (ArithmeticException a) {
     
    }
    
  4. Match each situation in the first list with an item in the second list.
    1. int[] A;
      A[0] = 0;
    2. The JVM starts running your program, but the JVM can't find the Java platform classes. (The Java platform classes reside in classes.zip or rt.jar.)
    3. A program is reading a stream and reaches the end of stream marker.
    4. Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.
    1. __error
    2. __checked exception
    3. __compile error
    4. __no exception

    Exercises

    1. Add a readList method to ListOfNumbers.java. This method should read in int values from a file, print each value, and append them to the end of the vector. You should catch all appropriate errors. You will also need a text file containing numbers to read in.
    2. Modify the following cat method so that it will compile.
      public static void cat(File file) {
       RandomAccessFile input = null;
       String line = null;
       try {
       input = new RandomAccessFile(file, "r");
       while ((line = input.readLine()) != null) {
       System.out.println(line);
       }
       return;
       } finally {
       if (input != null) {
       input.close();
       }
       }
      }
      
    Check your answers.
« PreviousTrailNext »

Previous page: Summary
Next page: Basic I/O

AltStyle によって変換されたページ (->オリジナル) /