Ch11 Exceptions Flashcards
What is an exception?
An exception is an event that alters program flow.
What superclass (aside from Object) do all exceptions inherit from in Java?
java.lang.Throwable
What is an Error and what should it be used for?
Error means something went so horribly wrong that your program should not attempt to recover from it. For example, the disk drive “dissapeared” or the program ran out of memory.
What is a checked exception?
A checked exception is an exception that must be declared or handled by the application code where it is thrown.
What do all checked exceptions inherit from?
Checked exceptions all inherit Exception (and thus also Throwable & Object)
What is an unchecked exception?
An unchecked exception is any exception that does not need to be declared or handled by the application code where it is thrown.
They are also known as runtime exceptions.
What do all unchecked exceptions inherit from?
Unchecked exceptions all inherit from either RuntimeException or Error.
What is the difference between throw and throws?
Throw is used as a statement inside a code block to throw a new exception.
Throws is used at the end of a method declaration to indicate what exception it might throw.
When is the IOException thrown?
Is it checked or unchecked (runtime)?
Thrown programmatically when there is a problem reading or writing a file.
Checked.
When is the FileNotFoundException thrown?
Is it checked or unchecked (runtime)?
Subclass of IOException thrown programatically when code tries to reference a file that doesn’t exist.
Checked.
When is the StackOverflowError thrown?
Is it checked or unchecked (runtime)?
Thrown when a method calls itself too many times.
Unchecked.
When is the NoClassDefFoundError thrown?
Is it checked or unchecked (runtime)?
Thrown when the class that the code uses is available at compile time but not runtime.
Unchecked.
Does the following code compile?
try {
} catch (IllegalArgumentException e) {
} catch (NumberFormatException e) {
}
No because NumberFormatException is a subclass of IllegalArgumentException meaning it will never reach that catch clause even if NumberFormatException was thrown.
Does the following code compile?
try {
} catch (IllegalArgumentException e1) {
System.out.println(e1);
} catch (NumberFormatException e2) {
System.out.println(e1);
}
No because e1 is out of scope in the second catch block.
Does the following code compile?
try {
} catch (ArrayIndexOutOfBoundsException e | NumberFormatException e) {
}
No because only a single identifier is allowed for all exception types.
correct:
try {
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
}