Input, Output, and Exception Handling Flashcards

1
Q

What class is at the top of the exception hierarchy?

A

Throwable is at the top of the exception hierarchy.

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

Briefly explain how to use try and catch.

A

The try and catch statements work together. Program statements that you want to monitor for exceptions
are contained within a try block. An exception is caught using catch.

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

What is wrong with this fragment?

// …
vals[18] = 10;
catch (ArrayIndexOutOfBoundsException exc) {
// handle error
}

A

There is no try block preceding the catch statement.

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

What happens if an exception is not caught?

A

If an exception is not caught, abnormal program termination results.

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

What is wrong with this fragment?

class A extends Exception { …

class B extends A { …

// …

try {
// …
}
catch (A exc) { … }
catch (B exc) { … }

A

In the fragment, a superclass catch precedes a subclass catch. Since the superclass catch will catch all subclasses too, unreachable code is created.

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

Can an inner catch rethrow an exception to an outer catch?

A

Yes, an exception can be rethrown.

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

The finally block is the last bit of code executed before your program ends. True or False? Explain your answer.

A

False. The finally block is the code executed when a try block ends.

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

What type of exceptions must be explicitly declared in a throws clause of a method?

A

All exceptions except those of type RuntimeException and Error must be declared in a throws clause.

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

What is wrong with this fragment?

class MyClass { // … }
// …
throw new MyClass();

A

MyClass does not extend Throwable. Only subclasses of Throwable can be thrown by throw.

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

In question 3 of the Chapter 6 Self Test, you created a Stack class. Add custom exceptions to your class that report stack full and stack empty conditions.

A

// An exception for stack-full errors.
class StackFullException extends Exception {
int size;

StackFullException(int s) { size = s; }

public String toString() {
return “\nStack is full. Maximum size is “ +
size;
}
}
// An exception for stack-empty errors.
class StackEmptyException extends Exception {

public String toString() {
return “\nStack is empty.”;
}
}

// A stack class for characters.
class Stack {
private char[] stck; // this array holds the stack
private int tos; // top of stack

// Construct an empty Stack given its size.
Stack(int size) {
stck = new char[size]; // allocate memory for stack
tos = 0;
}

// Construct a Stack from a Stack.
Stack(Stack ob) {
tos = ob.tos;
stck = new char[ob.stck.length];

// copy elements
for(int i=0; i < tos; i++)
  stck[i] = ob.stck[i];   }

// Construct a stack with initial values.
Stack(char[] a) {
stck = new char[a.length];

for(int i = 0; i < a.length; i++) {
  try {
    push(a[i]);
  }
  catch(StackFullException exc) {
    System.out.println(exc);
  }
}   }

// Push characters onto the stack.
void push(char ch) throws StackFullException {
if(tos==stck.length)
throw new StackFullException(stck.length);
stck[tos] = ch;
tos++;
}

// Pop a character from the stack.
char pop() throws StackEmptyException {
if(tos==0)
throw new StackEmptyException();
tos–;
return stck[tos];
}
}

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

What are the three ways that an exception can be generated?

A

An exception can be generated by an error in the JVM, by an error in your program, or explicitly via
a throw statement.

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

What are the two direct subclasses of Throwable?

A

Error and Exception

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

What is the multi-catch feature?

A

The multi-catch feature allows one catch clause to catch two or more exceptions.

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

Should your code typically catch exceptions of type Error?

A

No.

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

Why does Java define both byte and character streams?

A

The byte streams are the original streams defined by Java. They are especially useful for binary I/O,
and they support random-access files. The character streams are optimized for Unicode.

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

Even though console input and output is text-based, why does Java still use byte streams for this purpose?

A

The predefined streams, System.in, System.out, and System.err, were defined before Java added the
character streams.

17
Q

Show how to open a file for reading bytes.

A

Here is one way to open a file for byte input:

FileInputStream fin = new FileInputStream(“test”);

18
Q

Show how to open a file for reading characters.

A

Here is one way to open a file for reading characters:

FileReader fr = new FileReader(“test”);

19
Q

Show how to open a file for random-access I/O.

A

Here is one way to open a file for random access:

randfile = new RandomAccessFile(“test”, “rw”);

20
Q

How do you convert a numeric string such as “123.23” into its binary equivalent?

A

To convert numeric strings into their binary equivalents, use the parsing methods defined by the type wrappers, such as Integer or Double.

21
Q

Write a program that copies a text file. In the process, have it convert all spaces into hyphens. Use the byte stream file classes. Use the traditional approach to closing a file by explicitly calling close( ).

A

/* Copy a text file, substituting hyphens for spaces.

This version uses byte streams.

To use this program, specify the name
of the source file and the destination file.
For example,

java Hyphen source target
*/

import java.io.*;

class Hyphen {
public static void main(String[] args)
{
int i;
FileInputStream fin = null;
FileOutputStream fout = null;

// First make sure that both files have been specified.
if(args.length !=2 ) {
  System.out.println("Usage: Hyphen From To");
  return;
}

// Copy file and substitute hyphens.
try {
  fin = new FileInputStream(args[0]);
  fout = new FileOutputStream(args[1]);

  do {
    i = fin.read();

    // convert space to a hyphen
    if((char)i == ' ') i = '-';

    if(i != -1) fout.write(i);
  } while(i != -1);
} catch(IOException exc) {
  System.out.println("I/O Error: " + exc);
} finally {
  try {
    if(fin != null) fin.close();
  } catch(IOException exc) {
    System.out.println("Error closing input file."); 
  } 

  try {
    if(fin != null) fout.close();
  } catch(IOException exc) {
    System.out.println("Error closing output file.");
  }
}   } }
22
Q

Rewrite the program in question 7 so that it uses the character stream classes. This time, use the try-with-resources statement to automatically close the file.

A

/* Copy a text file, substituting hyphens for spaces.

This version uses character streams.

To use this program, specify the name
of the source file and the destination file.
For example,

java Hyphen2 source target

*/

import java.io.*;

class Hyphen2 {
public static void main(String[] args)
throws IOException
{
int i;

// First make sure that both files have been specified.
if(args.length !=2 ) {
  System.out.println("Usage: CopyFile From To");
  return;
} // Copy file and substitute hyphens.
// Use the try-with-resources statement.
try (FileReader fin = new FileReader(args[0]);
     FileWriter fout = new FileWriter(args[1]))
{
  do {
    i = fin.read();

    // convert space to a hyphen 
    if((char)i == ' ') i = '-'; 

    if(i != -1) fout.write(i);
  } while(i != -1);
} catch(IOException exc) {
  System.out.println("I/O Error: " + exc);
}
23
Q

What type of stream is System.in?

A

InputStream

24
Q

What does the read( ) method of InputStream return when an attempt is made to read at the end of the stream?

A

–1

25
Q

What type of stream is used to read binary data?

A

DataInputStream

26
Q

Reader and Writer are at the top of the ____________ class hierarchies.

A

character-based I/O

27
Q

The try-with-resources statement is used for ___________ ____________ ____________.

A

automatic resource management

28
Q

If you are using the traditional method of closing a file, then closing a file within a finally block is generally a good approach. True or False?

A

True