Try Catch Block Java 8 Certification

Try Catch Block (on Try Catch Block Java 8 Certification Exam) is most widely used statement when it comes to manage exception. Atry statement must have catch and/or finally.Having both is fine. Having neither is a problem. On the OCP exam, youlllearn about a special syntax for a try statement called try-with-resourcesthat allows neither a catch nor a finally block. On the OCA exam, you get to assume a try statement is just a regular try statement and not a try with resources statement.

java try catch structure

Using a try Statement

Now that you know what exceptions are, lets explore how to handle them. Java uses a trystatement to separate the logic that might throw an exception from the logic to handle thatexception. Below figure shows the syntax of a try statement.

The code in the try block is run normally. If any of the statements throw an exceptionthat can be caught by the exception type listed in the catch block, the try block stops runningand execution goes to the catch statement. If none of the statements in the try block throw an exception that can be caught, the catch clause is not run.You probably noticed the words block and clause used interchangeably. The exam does this as well, so we are getting you used to it. Both are correct. Block iscorrect because there are braces present. Clause is correct because they are part of atry statement. There arent a ton of syntax rules here. The curly braces are required for the try andcatch blocks.In this example, the little girl gets up by herself the first time she falls. Heres what thislooks like:

3: void explore() {
4: try {
5: fall();
6: System.out.println("never get here");
7: } catch (RuntimeException e) {
8: getUp();
9: }
10: seeAnimals();
11: }
12: void fall() { throw new RuntimeException(); }

First, line 5 calls the fall() method. Line 12 throws an exception. This means Javajumps straight to the catch block, skipping line 6. The girl gets up on line 8. Now the trystatement is over and execution proceeds normally with line 10.Now lets look at some invalid try statements that the exam might try to trick you with.Do you see whats wrong with this one?

try // DOES NOT COMPILE
fall();
catch (Exception e)
System.out.println("get up");
The problem is that the braces are missing. It needs to look like this:
try {
fall();
} catch (Exception e) {
System.out.println("get up");
}

try statements are like methods in that the curly braces are required even if there is onlyone statement inside the code blocks. if statements and loops are special in this respect asthey allow you to omit the curly braces.What about this one?

try {// DOES NOT COMPILE
fall();
}

This code doesnt compile because the try block doesnt have anything after it.Remember, the point of a try statement is for something to happen if an exception isthrown. Without another clause, the try statement is lonely.Now that you know the basics, lets start adding more features to exceptions. The followingsections show you how to add a finally clause to a try statement and catch different types of exceptions and describe what happens if an exception is thrown in catch or finally.

Adding a finally Block

try catch finally block

The try statement also lets you run code at the end with a finally clause regardless ofwhether an exception is thrown. Figure 6.3 shows the syntax of a try statement with thisextra functionality.

There are two paths through code with both a catch and a finally. If an exceptionis thrown, the finally block is run after the catch block. If no exception is thrown, thefinally block is run after the try block completes.Lets go back to our young girl example, this time with finally:

12: void explore() {
13: try {
14:   seeAnimals();
15:   fall();
16: } catch (Exception e) {
17:   getHugFromDaddy();
18: } finally {
19:   seeMoreAnimals();
20: }
21: goHome();
22: }

The girl falls on line 15. If she gets up by herself, the code goes on to the finally blockand runs line 19. Then the try statement is over and the code proceeds on line 21. If thegirl doesnt get up by herself, she throws an exception. The catch block runs and she gets a hug on line 17. Then the try statement is over and the code proceeds on line 21. Either way,the ending is the same. The finally block is executed and the try statement ends.

The exam will try to trick you with missing clauses or clauses in the wrong order. Doyou see why the following do or do not compile?

25: try { // DOES NOT COMPILE
26: fall();
27: } finally {
28: System.out.println("all better");
29: } catch (Exception e) {
30: System.out.println("get up");
31: }
32:
33: try { // DOES NOT COMPILE
34: fall();
35: }
36:
37: try {

38: fall();
39: } finally {
40: System.out.println("all better");
41: }

The first example (lines 2531) does not compile because the catch and finally blocks are in the wrong order. The second example (lines 3335) does not compile because theremust be a catch or finally block. The third example (lines 3741) is just fine. catch is not required if finally is present.

One problem with finally is that any realistic uses for it are out of the scope of theOCA exam. finally is typically used to close resources such as files or databasesboth ofwhich are topics on the OCP exam. This means most of the examples you encounter on the OCA exam with finally are going to look contrived. For example, youll get asked questionssuch as what this code outputs:

String s = "";
try {
s += "t";
} catch(Exception e) {
s += "c";
} finally {
s += "f";
}
s += "a";
System.out.print(s);

The answer is tfa. The try block is executed. Since no exception is thrown, Java goesstraight to the finally block. Then the code after the try statement is run. We know; thisis a silly example. Expect to see examples like this on the OCA exam.

System.exit

There is one exception to the finally block always runs after the catch block rule:Java defines a method that you call as System.exit(0);. The integer parameter is theerror code that gets returned. System.exit tells Java, Stop. End the program right now. Do not pass go. Do not collect $200. When System.exit is called in the try or catchblock, finally does not run.

Catching Various Types of Exceptions

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 defi ne basic exceptions to show you the hierarchy. You onlyneed to do two things with this information. First, you must be able to recognize 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 : Exception in Java Certification

Next Java Certification Chapter : Complex Exception Handling 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