Exceptions Flashcards
What exception does zero division lead to?
ArithmeticException
What exception does an invalid array index lead to?
ArrayIndexOutOfBoundsException
What exception occurs from using an object reference that hasn’t been assigned?
NullPointerException
When does NullPointerException occur?
When an attempt is made to used an object reference that hasn’t been assigned to an object
What exception occurs when a specific file doesn’t exist?
FileNotFoundException
How do exceptions occur and what do they contain?
The method creates a new exception object which is handed off to the runtime system.
This object contains information about the state of the program when it occur and the method-call stack.
What is the hierarchy of Java exceptions?
All derive from Throwable.
Errors are those that happen in JVM. They should not be caught be applications as they tend to be unrecoverable.
Exceptions represent situations that occur in a Java program.
How are exceptions caught?
A method can catch them directly using a try … catch … block.
Otherwise they are passed up the call stack to their calling method, eventually reaching the Java default handler.
What is the structure of a try-catch block?
try { … } catch (Exception e) { };
n.b. can have multiple catch blocks to handle different exceptions
What happens if multiple catch clauses match the exception raised?
The first one is matched and handled
What exception is raised if a number cannot be parsed?
NumberFormatException
What is important to note when using multiple catch clauses?
Specific ones must come before more general ones - otherwise a compile time error is raised
What is the effect of nested try..catch blocks?
It allows the handling of errors that occur within the catch clauses, such as if they re throw the exception
What is the effect of a finally block?
it is guaranteed to be executed. This allows the cleanup of actions that occurred in the try block.
Notably it is still called even if the code in the try block includes return, continue or break
How are exceptions triggered?
Using the “throw” keyword.
Exceptions are objects so it is common to go: throw new Exception(‘…’);