Common Exception Java 8 Certification

You need to recognise three types of exceptions for the OCA exam: run-time exceptions,checked exceptions, and errors. Well look at common examples of each type. For theexam, youll need to recognise which type of an exception it is and whether its thrown by the JVM or a programmer. So you can recognise them, well show you some code examplesfor those exceptions.

Runtime Exceptions

Runtime exceptions extend RuntimeException. They dont have to be handled or declared.They can be thrown by the programmer or by the JVM. Common runtime exceptionsinclude the following:

  1. ArithmeticException Thrown by the JVM when code attempts to divide by zeroArrayIndexOutOfBoundsException Thrown by the JVM when code uses an illegalindex to access an array
  2. ClassCastException Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance
  3. IllegalArgumentException Thrown by the programmer to indicate that a method hasbeen passed an illegal or inappropriate argument
  4. NullPointerException Thrown by the JVM when there is a null reference where anobject is required
  5. NumberFormatException Thrown by the programmer when an attempt is made to converta string to a numeric type but the string doesnt have an appropriate format


Trying to divide an int by zero gives an undefi ned result. When this occurs, the JVM willthrow an ArithmeticException: int answer = 11 / 0;Running this code results in the following output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Java doesnt spell out the word divide. Thats okay, though, because we know that / isthe division operator and that Java is trying to tell us division by zero occurred.The thread “main” is telling us the code was called directly or indirectly from a programwith a main method. On the OCA exam, this is all the output we will see. Next comes thename of the exception, followed by extra information (if any) that goes with the exception.


You know by now that array indexes start with 0 and go up to 1 less than the length of thearraywhich means this code will throw an ArrayIndexOutOfBoundsException:

int[] countsOfMoose = new int[3];

This is a problem because theres no such thing as a negative array index. Running thiscode yields the following output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

At least Java tells us what index was invalid. Can you see whats wrong with this one?

int total = 0;
int[] countsOfMoose = new int[3];
for (int i = 0; i = countsOfMoose.length; i++)
total += countsOfMoose[i];

The problem is that the for loop should have instead of =. On the final iteration ofthe loop, Java tries to call countsOfMoose[3], which is invalid. The array includes onlythree elements, making 2 the largest possible index. The output looks like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Java tries to protect you from impossible casts. This code doesnt compile because Integeris not a subclass of String:

String type = "moose";
Integer number = (Integer) type; // DOES NOT COMPILE

More complicated code thwarts Javas attempts to protect you. When the cast fails atruntime, 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 compilerdoesnt realize theres a String in that Object. When the code runs, it yields the followingoutput:

Exception in thread "main" java.lang.ClassCastException: java.lang.String
cannot be cast to java.lang.Integer

Java tells us both types that were involved in the problem, making it apparent whatswrong.


IllegalArgumentException is a way for your program to protect itself. We first saw thefollowing setter method in the Swan class in previous topics, Methods and Encapsulation.

6: public void setNumberEggs(int numberEggs) {// setter
7: if (numberEggs = 0) // guard condition
8: this.numberEggs = numberEggs;
9: }

This code works, but we dont really want to ignore the callers request when they tellus a Swan has 2 eggs. We want to tell the caller that something is wrongpreferably in avery obvious way that the caller cant ignore so that the programmer will fix the problem. Exceptions are an efficient way to do this. Seeing the code end with an exception is a greatreminder that something is wrong:

public static void setNumberEggs(int numberEggs) {
if (numberEggs  0)
throw new IllegalArgumentException(
"# eggs must not be negative");
this.numberEggs = numberEggs;

The program throws an exception when its not happy with the parameter values. Theoutput looks like this:

Exception in thread "main" java.lang.IllegalArgumentException: # eggs must notbe negative

Clearly this is a problem that must be fi xed if the programmer wants the program to doanything useful.


Instance variables and methods must be called on a non-null reference. If the reference isnull, the JVM will throw a NullPointerException. Its usually subtle, such as this example,which checks whether you remember instance variable references default to null.

String name;
public void printLength() throws NullPointerException {

Running this code results in this output:

Exception in thread "main" java.lang.NullPointerException


Java provides methods to convert strings to numbers. When these are passedan invalid value, they throw a NumberFormatException. The idea is similar toIllegalArgumentException. Since this is a common problem, Java gives it a separate class. In fact, NumberFormatException is a subclass of IllegalArgumentException. Heres anexample of trying to convert something non-numeric into an int:


The output looks like this:

Exception in thread "main" java.lang.NumberFormatException: For input string:"abc"

All OCJP Java Certification Tutorials

  1. Oracle (OCJP) Java Certification Exam
  2. Java Building Blocks Java 8 Certification
  3. Operators And Statements
  4. Java Core API
  5. Java Class Design
  6. Java Exception
  7. Java Try-Catch Block
  8. Exceptional Handling in Java
  9. Common Exception in Java