Exceptions Flashcards
Happy Path
The path through the code where exceptions are not thrown
Runtime Exception
Tend to be unexpected, but not necessarily fatal.
Also called unchecked exceptions.
Includes RuntimeException and all its subclasses
Checked Exception
Includes Exception and all subclasses that do not extend RuntimeException
Handle or Declare Rule
A rule enforced by the compiler that states if a statement throws a checked exception, it must attempt to catch the exception or declare the exception in the method declaration using the throws keyword.
throws
Indicates that the code might throw the specified exception, but it might not
For Runtime Exception…
1) How to recognize?
2) Okay for program to catch?
3) Is program required to handle or declare?
1) Subclass of RuntimeException
2) Yes
3) No
For Checked Exception…
1) How to recognize?
2) Okay for program to catch?
3) Is program required to handle or declare?
1) Subclass of Exception but not subclass of RuntimeException
2) Yes
3) Yes
For Error…
1) How to recognize?
2) Okay for program to catch?
3) Is program required to handle or declare?
1) Subclass of Error
2) No
3) No
try statement syntax
try { //code } catch (exception_type e) { //code }
must have the braces!
What must go along with a try block?
Either a catch block or a finally block.
Note: You don’t need both! You can even just have a try and finally with no catch. You can also have multiple catch blocks
If there are multiple catch blocks, you must watch out for….
Superclasses being handled before subclasses.
For example, every exception class extends from the class Exception, so if you were to catch an Exception before any others, then the catch statements would be unreachable and the compiler would say no no
ArithmeticException
Thrown by the JVM when code attempts to divide by 0
RuntimeException
ArrayIndexOutOfBoundsException
Thrown by the JVM when code uses an illegal index to access an array
RuntimeException
ClassCastException
Thrown by the JVM when an attempt is made to cast something to a subclass of which it is not an instance
RuntimeException
String type = “moose”;
Integer number = (Integer) type; // DOES NOT COMPILE
More complicated code thwarts Java’s attempts to protect you. When the cast fails at runtime, Java will throw a ClassCastException:
String type = “moose”;
Object obj = type;
Integer number = (Integer) obj;
The compiler sees a cast from Object to Integer. This could be okay. The compiler doesn’t realize there’s a String in that Object.
IllegalArgumentException
Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument
Checked Exception