OCA Java SE 8 Exception - Java Exception Types








Runtime Exceptions

Runtime exceptions extend RuntimeException. They don't have to be handled or declared.

They can be thrown by the programmer or by the JVM. Common runtime exceptions include the following:

  • ArithmeticException Thrown by the JVM when code attempts to divide by zero
  • ArrayIndexOutOfBoundsException Thrown by the JVM when code uses an illegal index to access an array
  • ClassCastException Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance
  • IllegalArgumentException Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument
  • NullPointerException Thrown by the JVM when there is a null reference where an object is required
  • NumberFormatException Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn't have an appropriate format
  • ArithmeticException Trying to divide an int by zero gives an undefined result. When this occurs, the JVM will throw an ArithmeticException:
  • ArrayIndexOutOfBoundsException array indexes start with 0 and go up to 1 less than the length of the array-which means this code will throw an ArrayIndexOutOfBoundsException:
  • ClassCastException Cannot cast exception from one type to another type
  • IllegalArgumentException Happens when the parameters are wrong.
  • NullPointerException If the reference is null, the JVM will throw a NullPointerException.
  • NumberFormatException Thrown when cannot format numbers

When these are passed an invalid value to format, Java throws a NumberFormatException.





Checked Exceptions

Checked exceptions have Exception in their hierarchy but not RuntimeException.

Checked exceptions must be handled or declared.

Checked exceptions can be thrown by the programmer or by the JVM.

Common runtime exceptions include the following:

  • FileNotFoundException Thrown programmatically when code tries to reference a file that does not exist
  • IOException Thrown programmatically when there's a problem reading or writing a file

Errors

Errors extend the Error class. They are thrown by the JVM and should not be handled or declared.

Errors you might see:

  • ExceptionInInitializerError Thrown by the JVM when a static initializer throws an exception and doesn't handle it
  • StackOverflowError Thrown by the JVM when a method calls itself too many times
  • NoClassDefFoundError Thrown by the JVM when a class that the code uses is available at compile time but not runtime
  • ExceptionInInitializerError If one of the static initializers throws an exception.