Chapter 14 - Exception Handling and Text I/O Flashcards

1
Q

How do the ‘try’, ‘catch’, and ‘finally’ statements interact?

A
Example:
try {
Code to run;
Statement or method that may throw an exception;
More code to run if no exception;
}

catch (exceptionType ex) {
Code to process the exception;
}

finally {
This code always runs, whether or not an exception is thrown in the try statement.
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are exceptions?

A

They are objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe the exception classes hierarchy

A
Throwable is the root exception class (it's superclass is Object).
Exception and Error are Throwable's subclasses.
Error contains subclasses that describe system errors.
Exception contains subclasses that describe errors caused by your program and by external circumstances.
One of Exception's subclasses is RuntimeException.
RuntimeException contains subclasses that describe programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a checked exception?

A

A checked exception is an exception that the compiler forces the programmer to deal with, either with a try-catch block or declare it in the method header.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which exception classes are checked, and which are unchecked?

A

RuntimeException and Error, and their subclasses are unchecked exceptions. All other exceptions classes are checked.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you deal with checked exceptions?

A
You can either catch it in an ordinary try statement, like this:
public static void openFile(String name)
{
    try
    {
        FileInputStream f = 
            new FileInputStream(name);
    }
    catch (FileNotFoundException e)
    {
        System.out.println(“File not found.”);
    }
}
or, if you don't want to deal with the exception in the method that creates the exception, you can throw it "up the line", back to the caller like this:
public static void openFile(String name)
    throws FileNotFoundException
{
    FileInputStream f = 
        new FileInputStream(name);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is important in regards to the order of catch blocks?

A

Catch blocks that catch a superclass exception must appear after a catch block for a subclass exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When should you use exceptions?

A

A method should throw an exception if the error needs to be handled by its caller.
If you can handle the exception in the method where it occurs, there is no need to throw or use exceptions.
In general, common eceptions that may occur in multiple classes in a project are candidates for exception classes. Simple errors that may occur in individual methods are best handled without throwing exceptions – by using if statements to check for errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is meant by “rethrowing exceptions”?

A

Java allows an exception handler to rethrow the exception if the handler cannot process the exception or simply wants to let its caller be notified of the exception. The syntax looks like this:
try {
statements;
}

catch (TheException ex) {
perform operations before exits;
throw ex;
}

The statement “throw ex;” rethrows the exception back to the caller so that other handlers in the caller get a chance to process the exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

When should you create your own exception class?

A

You should use the built-in exception classes whenever possible, but if you run into a problem that cannot be adequately described by the exception classes, you can create your own exception class, derived from Exception or from a subclass of Exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you create your own exception class?

A
By extending Exception or one of its subclasses.
Example:
public class InvalidRaidusException extends Exception {
    private double radius;
    /** Construct an exception */
    public InvalidRadiusException(double radius) {
        super("Invalid radius " + radius);
        this.radius = radius;
    }
}

You can then create a setRadius method that looks like this:
public void setRadius(double newRadius) throws InvalidRadiusException {
if (newRadius >= 0)
radius = newRadius;
else
throw new InvalidRadiusException(newRadius);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What can you do with the File class?

A
The File class contains the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory.
It does not contain the methods for creating a file or for writing/reading data to/from a file.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Why shouldn’t you use absolute file names in your program?

A

Because file path syntax is different for different platforms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you create a file and write to it?

A

You use the java.io.PrintWriter class.
PrintWriter output = new PrinterWriter(fileName);
to create the file fileName (which can be a File object).
output.println(“ost”);
output.print(“ost”);
to write to the file.
Remember to close the file when finished, with:
output.close();
Note that checked exceptions may be thrown.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you read from a file?

A

You use the java.util.Scanner class.
To read from a file, create a Scanner for a file, as follows:
Scanner input = new Scanner(new File(filename));
or if File object is already created:
Scanner input = new Scanner(filename);
Note that checked exceptions may be thrown.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a file dialog, and how do you create one?

A
A file dialog displays a window that lets the user choose a file. You use the javax.swing.JFileChooser class to create file dialogs:
JFileChooser fileChooser = new JFileChooser();
The method fileChooser.showOpenDialog(null); is the method that displays the dialog window.
17
Q

How do you read data from the web?

A
First you have to create a URL object using the java.net.URL class, with this constructor:
public URL(String urladress) throws MalformedURLException, like this:
URL url = new URL("http://www.blabla.com");
After the URL object is created, you can use the openStream() method defined in the URL class to open an input stream and use this stream to create a Scanner object as follows:
Scanner input = new Scanner(url.openStream());
Now you can read the data from the input stream just like from a local file.
Remember that checked exceptions may be thrown.
18
Q

An instance of ____ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

A

Error

19
Q

An instance of ___ describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program.

A

Exception

20
Q

An instance of ___ describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

A

RuntimeException

21
Q
What exception type does the following program throw?
public class Test {
  public static void main(String[] args) {
    System.out.println(1 / 0);
  }
A

ArithmeticException

22
Q
What exception type does the following program throw?
public class Test {
  public static void main(String[] args) {
    int[] list = new int[5];
    System.out.println(list[5]);
  }
}
A

ArrayIndexOutOfBoundsException

23
Q

Which of the following statements are true?
A. You use the keyword throws to declare exceptions in the method heading.
B. A method may declare to throw multiple exceptions.
C. To throw an exception, use the key word throw.
D. If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method.

A

All are true.

24
Q

Analyze the following code:

class Test {
  public static void main(String[] args) {
    try {
      String s = "5.6";
      Integer.parseInt(s); // Cause a NumberFormatException
      int i = 0;
      int y = 2 / i;
    }
    catch (Exception ex) {
      System.out.println("NumberFormatException");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
  }

A. The program displays NumberFormatException.
B. The program displays RuntimeException.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compilation error.

A
D. The program has a compilation error.
The RuntimeException catch block should appear before the Exception catch block. Subclass before superclass.
25
Q

What is displayed on the console when running the following program?

class Test {
  public static void main(String[] args) {
    try {
      method();
      System.out.println("After the method call");
    }
    catch (NumberFormatException ex) {
      System.out.println("NumberFormatException");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
  }

static void method() {
String s = “5.6”;
Integer.parseInt(s); // Cause a NumberFormatException

    int i = 0;
    int y = 2 / i;
    System.out.println("Welcome to Java");
  }
}

A. The program displays NumberFormatException.
B. The program displays NumberFormatException followed by After the method call.
C. The program displays NumberFormatException followed by RuntimeException.
D. The program has a compilation error.
E. The program displays RuntimeException.

A

A. The program displays NumberFormatException.

26
Q
class Test {
  public static void main(String[] args) {
    try {
      method();
      System.out.println("After the method call");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
    catch (Exception ex) {
      System.out.println("Exception");
    }
  }

static void method() throws Exception {
try {
String s = “5.6”;
Integer.parseInt(s); // Cause a NumberFormatException

      int i = 0;
      int y = 2 / i;
      System.out.println("Welcome to Java");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
    catch (Exception ex) {
      System.out.println("Exception");
    }
  }
}

A. The program displays RuntimeException twice.
B. The program displays Exception twice.
C. The program displays RuntimeException followed by After the method call.
D. The program displays Exception followed by RuntimeException.
E. The program has a compilation error.

A

C. The program displays RuntimeException followed by After the method call.
Because the exception created inside the method is handled inside the method, the caller (try block in main method) continues its execution.

27
Q

What is wrong in the following program?

class Test {
  public static void main (String[] args) {
    try {
      System.out.println("Welcome to Java");
     }
  }
}
A

You cannot have a try block without a catch block or a finally block.

28
Q

What is displayed on the console when running the following program?

class Test {
  public static void main(String[] args) {
    try {
      System.out.println("Welcome to Java");
      int i = 0;
      int y = 2/i;
      System.out.println("Welcome to Java");
    }
    catch (RuntimeException ex) {
      System.out.println("Welcome to Java");
    }
    finally {
      System.out.println("End of the block");
    }
  }
}
A

“Welcome to Java” twice, followed by “End of the block”.

29
Q

What is displayed on the console when running the following program?

class Test {
  public static void main(String[] args) {
    try {
      method();
      System.out.println("After the method call");
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
    catch (Exception ex) {
      System.out.println("Exception");
    }
  }

static void method() throws Exception {
try {
String s = “5.6”;
Integer.parseInt(s); // Cause a NumberFormatException

      int i = 0;
      int y = 2 / i;
      System.out.println("Welcome to Java");
    }
    catch (NumberFormatException ex) {
      System.out.println("NumberFormatException");
      throw ex;
    }
    catch (RuntimeException ex) {
      System.out.println("RuntimeException");
    }
  }
}
A

The program displays NumberFormatException followed by RuntimeException.

30
Q

What are the reasons to create an instance of the File class?
A. To determine whether the file exists.
B. To obtain the properties of the file such as whether the file can be read, written, or is hidden.
C. To rename the file.
D. To delete the file.
E. To read/write data from/to a file

A

All except E.

31
Q
Which of the following statements are true?
A. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") returns null.
B. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") returns null.
C. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") creates a new file named c:\temp.txt.
D. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang.
E. None of the above.
A

E. None of the above.

32
Q
Which class contains the method for checking whether a file exists?
A. File
B. PrintWriter
C. Scanner
D. System
A

A. File.

33
Q
Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code.
Scanner input = new Scanner(System.in);
int v1 = input.nextInt();
int v2 = input.nextInt();
String line = input.nextLine();
A. After the last statement is executed, intValue is 34.
B. The program has a runtime error because 34.3 is not an integer.
C. After the last statement is executed, line contains characters '7', '8', '9', '\n'.
D. After the last statement is executed, line contains characters '7', '8', '9'.
A

B. The program has a runtime error because 34.3 is not an integer.