Exception Handling Java 8 Certification

Exception Handling Java 8 Certification (or Catching Various Types of Exceptions) is an key aspect of application development when working with Java.So far, you have been catching only one type of exception. Now lets see what happenswhen different types of exceptions can be thrown from the same method.Creating your own exceptions is not on the OCA exam, but it is on the OCP exam.However, the OCA exam can define basic exceptions to show you the hierarchy.

java-exception-cartoon

You onlyneed to do two things with this information. First, you must be able to recognise if theexception is a checked or an unchecked exception. Second, you need to determine if any ofthe exceptions are subclasses of the others.

class AnimalsOutForAWalk extends RuntimeException { }
class ExhibitClosed extends RuntimeException { }
class ExhibitClosedForLunch extends ExhibitClosed { }

In this example, there are three custom exceptions. All are unchecked exceptionsbecause they directly or indirectly extend RuntimeException. Now we catch both types ofexceptions and handle them by printing out the appropriate message:

public void visitPorcupine() {
try {
seeAnimal();
} catch (AnimalsOutForAWalk e) {// first catch block
System.out.print("try back later");
} catch (ExhibitClosed e) {// second catch block
System.out.print("not today");
}
}

There are three possibilities for when this code is run. If seeAnimal() doesnt throw anexception, nothing is printed out. If the animal is out for a walk, only the first catch blockruns. If the exhibit is closed, only the second catch block runs.A rule exists for the order of the catch blocks. Java looks at them in the order theyappear. If it is impossible for one of the catch blocks to be executed, a compiler errorabout unreachable code occurs. This happens when a superclass is caught before a subclass.Remember, we warned you to pay attention to any subclass exceptions.In the porcupine example, the order of the catch blocks could be reversed because theexceptions dont inherit from each other. And yes, we have seen a porcupine be taken for awalk on a leash.The following example shows exception types that do inherit from each other:

public void visitMonkeys() {
try {
seeAnimal();
} catch (ExhibitClosedForLunch e) {// subclass exception
System.out.print("try back later");
} catch (ExhibitClosed e) {// superclass exception
System.out.print("not today");
}
}

If the more specifi c ExhibitClosedForLunch exception is thrown, the first catchblock runs. If not, Java checks if the superclass ExhibitClosed exception is thrownand catches it. This time, the order of the catch blocks does matter. The reverse doesnot work.

public void visitMonkeys() {
try {
      seeAnimal();
} catch (ExhibitClosed e) {
     System.out.print("not today");
} catch (ExhibitClosedForLunch e) {// DOES NOT COMPILE
     System.out.print("try back later");
}
}

This time, if the more specific ExhibitClosedForLunch exception is thrown, the catchblock for ExhibitClosed runswhich means there is no way for the second catch block toever run. Java correctly tells us there is an unreachable catch block. Lets try this one more time. Do you see why this code doesnt compile?

public void visitSnakes() {
	try {
		seeAnimal();
	} catch (RuntimeException e) {
		System.out.print("runtime exception");
	} catch (ExhibitClosed e) {// DOES NOT COMPILE
		System.out.print("not today");
	} catch (Exception e) {
		System.out.print("exception");
	}
}

Its the same problem. ExhibitClosed is a RuntimeException. If it is thrown, the firstcatch block takes care of it, making sure there no way to get to the second catch block.To review catching multiple exceptions, remember that at most one catch block will runand it will be the first catch block that can handle it.

Throwing a Second Exception

So far, weve limited ourselves to one try statement in each example. However,a catch or finally block can have any valid Java code in itincluding anothertry statement.

The following code tries to read a file:

16: public static void main(String[] args) {
17: 	FileReader reader = null;
18: 	try {
19: 		reader = read();
20: 	} catch (IOException e) {
21: 	try {
22: 		if (reader != null) reader.close();
23: 	} catch (IOException inner) {
24: 	}
25: 	}
26: }
27: private static FileReader read() throws IOException {
28: 	// CODE GOES HERE
29: }

The easiest case is if line 28 doesnt throw an exception. Then the entire catch block onlines 2025 is skipped. Next, consider if line 28 throws a NullPointerException. That isntan IOException, so the catch block on lines 2025 will still be skipped.If line 28 does throw an IOException, the catch block on lines 2025 does get run. Line22 tries to close the reader. If that goes well, the code completes and the main() methodends normally. If the close() method does throw an exception, Java looks for more catchblocks. There arent any, so the main method throws that new exception. Regardless, theexception on line 28 is handled. A different exception might be thrown, but the one fromline 28 is done.Most of the examples you see with exception handling on the exam are abstract. They use letters or numbers to make sure you understand the fl ow. This one shows that only thelast exception to be thrown matters. (This is true for the OCA exam. It will change a bit onthe OCP exam.)

26: try {
27: 	throw new RuntimeException();
28: } catch (RuntimeException e) {
29: 	throw new RuntimeException();
30: } finally {
31: 	throw new Exception();
32: }

Line 27 throws an exception, which is caught on line 28. The catch block then throwsan exception on line 29. If there were no finally block, the exception from line 29 wouldbe thrown. However, the finally block runs after the try block. Since the finally block throws an exception of its own on line 31, this one gets thrown. The exception from thecatch block gets forgotten about. This is why you often see another try/catch inside afinally blockto make sure it doesnt mask the exception from the catch block. Next we are going to show you the hardest example you can be asked related toexceptions. What do you think this method returns? Go slowly. Its tricky.

30: public String exceptions() {
31: 	String result = "";
32: 	String v = null;
33: 	try {
34: 		try {
35: 			result += "before";
36: 			v.length();
37: 			result += "after";
38: 		}catch (NullPointerException e) {
39: 			result += "catch";
40: 			throw new RuntimeException();
41: 		} finally {
42: 			result += "finally";
43: 			throw new Exception();
44: 		}
45: 	} catch (Exception e) {
46: 		result += "done";
47: 	}
48: 	return result;
49: }

Previous Java Certification Chapter : Try Catch Block in Java

Next Java Certification Chapter : Common Exception in Java

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