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. A try statement must have catch and/or finally. Having both is fine. Having neither is a problem. On the OCP exam, you’ll learn about a special syntax for a try statement called try-with-resources that 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, let’s explore how to handle them. Java uses a try statement to separate the logic that might throw an exception from the logic to handle that exception. 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 exception that can be caught by the exception type listed in the catch block, the try block stops running and 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” is correct because there are braces present. “Clause” is correct because they are part of a try statement.
There aren’t a ton of syntax rules here. The curly braces are required for the try and catch blocks. In this example, the little girl gets up by herself the first time she falls. Here’s what this looks 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 Java jumps straight to the catch block, skipping line 6. The girl gets up on line 8. Now the try statement is over and execution proceeds normally with line 10. Now let’s look at some invalid try statements that the exam might try to trick you with. Do you see what’s 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 only one statement inside the code blocks. if statements and loops are special in this respect as they allow you to omit the curly braces. What about this one?

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

This code doesn’t compile because the try block doesn’t have anything after it. Remember, the point of a try statement is for something to happen if an exception is thrown. Without another clause, the try statement is lonely. Now that you know the basics, let’s start adding more features to exceptions. The following sections 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 of whether an exception is thrown. Figure 6.3 shows the syntax of a try statement with this extra functionality.

There are two paths through code with both a catch and a finally. If an exception is thrown, the finally block is run after the catch block. If no exception is thrown, the finally block is run after the try block completes.  Let’s 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 block and runs line 19. Then the try statement is over and the code proceeds on line 21. If the girl doesn’t 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. Do you 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 25–31) does not compile because the catch and finally blocks are in the wrong order. The second example (lines 33–35) does not compile because there must be a catch or finally block. The third example (lines 37–41) 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 the OCA exam. finally is typically used to close resources such as files or databases—both of which 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, you’ll get asked questions such 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 goes straight to the finally block. Then the code after the try statement is run. We know; this is 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 the error 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 catch block, finally does not run.

Catching Various Types of Exceptions

So far, you have been catching only one type of exception. Now let’s see what happens when 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 only need to do two things with this information. First, you must be able to recognize if the exception is a checked or an unchecked exception. Second, you need to determine if any of the 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 exceptions because they directly or indirectly extend RuntimeException. Now we catch both types of exceptions 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() doesn’t throw an exception, nothing is printed out. If the animal is out for a walk, only the first catch block runs. 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 they appear. If it is impossible for one of the catch blocks to be executed, a compiler error about 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 the exceptions don’t inherit from each other. And yes, we have seen a porcupine be taken for a walk 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 catch block runs. If not, Java checks if the superclass ExhibitClosed exception is thrown and catches it. This time, the order of the catch blocks does matter. The reverse does not 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 catch block for ExhibitClosed runs—which means there is no way for the second catch block to ever run. Java correctly tells us there is an unreachable catch block.
Let’s try this one more time. Do you see why this code doesn’t 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");
	}
}

It’s the same problem. ExhibitClosed is a RuntimeException. If it is thrown, the first catch 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 run and it will be the first catch block that can handle it.

Throwing a Second Exception

So far, we’ve limited ourselves to one try statement in each example. However, a catch or finally block can have any valid Java code in it—including another try 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 doesn’t throw an exception. Then the entire catch block on lines 20–25 is skipped. Next, consider if line 28 throws a NullPointerException. That isn’t an IOException, so the catch block on lines 20–25 will still be skipped. If line 28 does throw an IOException, the catch block on lines 20–25 does get run. Line 22 tries to close the reader. If that goes well, the code completes and the main() method ends normally. If the close() method does throw an exception, Java looks for more catch blocks. There aren’t any, so the main method throws that new exception. Regardless, the exception on line 28 is handled. A different exception might be thrown, but the one from line 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 the last exception to be thrown matters. (This is true for the OCA exam. It will change a bit on the 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 throws an exception on line 29. If there were no finally block, the exception from line 29 would be 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 the catch block gets forgotten about. This is why you often see another try/catch inside a finally block—to make sure it doesn’t mask the exception from the catch block.
Next we are going to show you the hardest example you can be asked related to exceptions. What do you think this method returns? Go slowly. It’s 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

Comments are closed.