Java SE 8 OCA exam: Chapter 6

I’ve decided to optimize my exam preparation by stuffing smaller chapters in times where I would normally rest. This chapter 6 is excellent candidate since it’s short and easy to understand.

Notes:

1.Pay special attention to code that calls a method on a null or that references an invalid array or ArrayList index. If you spot this, you know the correct answer is that the
code throws an exception.

2. On the exam, you will see two types of code that result in an exception. The frst is code
that’s wrong. For example:
String[] animals = new String[0];
System.out.println(animals[0]);

This code throws an ArrayIndexOutOfBoundsException. That means questions about
exceptions can be hidden in questions that appear to be about something else.

The second way for code to result in an exception is to explicitly request Java to throw
one. Java lets you write statements like these:
throw new Exception();
throw new Exception(“Ow! I fell.”);
throw new RuntimeException();
throw new RuntimeException(“Ow! I fell.”);

3.  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.

4.  Even though the topic of reading files is on the OCP exam, the OCA exam
may ask you about exception handling with those classes. This is actually a
gift. When you see such a question, you know the problem has to be about
basic Java syntax or exception handling!

5. For the exam, we’ll need to recognize which type of an exception it is and whether it’s thrown by the JVM or a programmer.
6.  If a try statement has multiple catch blocks, at most one catch block can run. Java
looks for an exception that can be caught by each
catch block in the order they appear, and
the frst match is run. Then execution continues after the
try statement. If both catch and
finally throw an exception, the one from finally gets thrown.

7. Note, NumberFormatException example is when we try to convert string to int. ex. Integer.parseInt(“abc”);

8.  When a method overrides a method in a superclass or interface, it is not allowed to add
checked exceptions. It is allowed to declare fewer exceptions or declare a subclass of a
declared exception. Methods declare exceptions with the keyword
throws.

9.  Identify whether an exception is thrown by the programmer or the JVM. Illegal
ArgumentException
and NumberFormatException are commonly thrown by the programmer. Most of the other runtime exceptions are typically thrown by the JVM

10.  Recognize when to use throw versus throws. The throw keyword is used when you actually want to throw an exception—for example, throw new RuntimeException(). The
throws keyword is used in a method declaration

11. If the method has exception that was not caught, that method will exit, but you must remember just before exiting the method, it will run the finally block.

12.

public void run() {
System.out.print(“1”);
try {
System.out.print(“2”);
name.toString();
System.out.print(“3”);
} catch (NullPointerException e) {
System.out.print(“4”);

}
System.out.print(“5”);
}

public static void main(String[] arg) {
Substitute jerry = new Substitute();
jerry.run();
System.out.print(“6”);}

Output is: 12456

13. Methods can return exception object

public Exception myExc(){
Exception e = new Exception();
return e;
}   // will compile and return some exception

14.

Which of the following can be inserted in the blank to make the code compile? (Choose all
that apply)
public static void main(String[] args) {
try {
System.out.println(“work real hard”);
} catch (______ e) {
} catch (RuntimeException e) {
}
}
A. Exception
B. IOException
C. IllegalArgumentException
D. RuntimeException
E. StackOverflowError
F. None of the above.

C, E. Option C is allowed because it is a more specific type than RuntimeException.
Option E is allowed because it isn’t in the same inheritance tree as RuntimeException. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the try block doesn’t declare an IOException to be thrown. The
compiler realizes that IOException would be an unreachable catch block. Option D
is not allowed because the same exception can’t be specified in two different catch
blocks. Finally, option A is not allowed because it’s more general than RuntimeException and would make that block unreachable.

15. What does the output of the following contain? (Choose all that apply)

12: public static void main(String[] args) {
13: System.out.print(“a”);
14: try {
15: System.out.print(“b”);
16: throw new IllegalArgumentException();
17: } catch (IllegalArgumentException e) {
18: System.out.print(“c”);
19: throw new RuntimeException(“1”);
20: } catch (RuntimeException e) {
21: System.out.print(“d”);
22: throw new RuntimeException(“2”);
23: } finally {
24: System.out.print(“e”);
25: throw new RuntimeException(“3”);
26: }
27: }
A. abce
B. abde
C. An exception with the message set to “1”
D. An exception with the message set to “2”
E. An exception with the message set to “3”
F. Nothing; the code does not compile.

A, E. The code begins normally and prints a on line 13, followed by b on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also
throws an exception, that’s the one printed.

ch6.PNG

ch6b.PNG

Checked vs Unchecked(Runtime) exceptions

Unchecked exceptions:

  • represent defects in the program (bugs) – often invalid arguments passed to a non-private method.  “Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program’s logic and cannot be reasonably recovered from at run time.”
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, orIllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)

Checked exceptions:

  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

Throwing an exception

 

ch6a.PNG

Try – Catch – Finally

Try always must have EITHER Catch or Finally. It can also have both of them.

Also Try must have { }

Finally will always run if it’s present

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

OCA exam can defne 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
 (aka Unreachable exceptions problem)

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

Unreachable exceptions

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.

public void visitMonkeys() {
try {
seeAnimal();
} catch (ExhibitClosed e) {
System.out.print(“not today”);
} catch (ExhibitClosedForLunch e) { // DOES NOT COMPILE because ExhibitClosed is superclass of ExhibitClosedForLunch
System.out.print(“try back later”);
}
}

However if subclass comes first then only superclass, then code will compile. The reason is that in the example above the ExhibitClosedForLunch is not reachable, because it’s subclass of ExhibitClosed

Same case below. ExhibitClosed extends RuntimeException, meaning RuntimeException will throw the exception and ExhibitClosed is not reachable.

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”);
}
}

Throwing a Second Exception

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.

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

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: }

The correct answer is before catch finally done. Everything is normal up until line
35, when
“before” is added. Line 36 throws a NullPointerException. Line 37 is skipped
as Java goes straight to the
catch block. Line 38 does catch the exception, and “catch” is
added on line 39. Then line 40 throws a
RuntimeException. The finally block runs after
the
catch regardless of whether an exception is thrown; it adds “finally” to result. At this
point, we have completed the inner
try statement that ran on lines 34–44. The outer catch
block then sees an exception was thrown and catches it on line 45; it adds “done” to result.

Recognizing Common Exception Types

There are 3 types of exceptions in Java: runtime exceptions, checked exceptions, and errors.

Runtime Exceptions

Runtime exceptions extend RuntimeException. Remember if the superclass preceeds the subclass in catch blocks then subclass becomes unreachable.

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

ex: 

int[] countsOfMoose = new int[3];
System.out.println(countsOfMoose[-1]);

ClassCastException Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance

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

String type = “moose”;
Object obj = type;
Integer number = (Integer) obj;

IllegalArgumentException Thrown by the programmer to indicate that a method has
been passed an illegal or inappropriate argument. Since it’s thrown by programmer, good way of looking at is, is to think of this exception as a guidance for good values, when the programmer sees the exception log.

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

Output:

Exception in thread “main” java.lang.IllegalArgumentException: # eggs must not
be negative

NullPointerException Thrown by the JVM when there is a null reference where an
object is required

String name;
public void printLength() throws NullPointerException {
System.out.println(name.length());
}

Exception in thread “main” java.lang.NullPointerException

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

NumberFormatException is a subclass of IllegalArgumentException!

Integer.parseInt(“abc”);
The output looks like this:
Exception in thread “main” java.lang.NumberFormatException: For input string:
“abc

Checked Exceptions

Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They 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 fle
that does not exist
IOException Thrown programmatically when there’s a problem reading or writing a fle

Also keep in mind that FileNotFoundException is a subclass of IOException, although the exam will remind you of that fact if it comes up.

Errors

Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared. Errors are rare, but you might see these:
ExceptionInInitializerError Thrown by the JVM when a static initializer throws
an exception and doesn’t handle it

static {
int[] countsOfMoose = new int[3];
int num = countsOfMoose[-1];
}
public static void main(String[] args) { }

Exception in thread “main” java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1

StackOverflowError Thrown by the JVM when a method calls itself too many times
(this is called
infnite recursion because the method typically calls itself without end)

public static void doNotCodeThis(int num) {
doNotCodeThis(1);
}
The output contains this line:
Exception in thread “main” java.lang.StackOverflowError
NoClassDefFoundError Thrown by the JVM when a class that the code uses is available
at compile time but not runtime

This error won’t show up in code on the exam—you just need to know that it is an error.
NoClassDefFoundError occurs when Java can’t fnd the class at runtime.

Calling Methods That Throw Exceptions

class NoMoreCarrotsException extends Exception {}
public class Bunny {
public static void main(String[] args) {
eatCarrot();// DOES NOT COMPILE because missing exception handling for the method //that throws NoMoreCarrotsException
}
private static void eatCarrot() throws NoMoreCarrotsException {
}
}

The problem is that NoMoreCarrotsException is a checked exception. Checked exceptions must be handled or declared. The code would compile if we changed the main()
method to either of these:
public static void main(String[] args)
throws NoMoreCarrotsException {// declare exception
eatCarrot();
}
public static void main(String[] args) {
try {
eatCarrot();
} catch (NoMoreCarrotsException e ) {// handle exception
System.out.print(“sad rabbit”);
}
}

You might have noticed that eatCarrot() didn’t actually throw an exception; it just
declared that it could. This is enough for the compiler to require the caller to handle or
declare the exception

public void bad() {
try {
eatCarrot();
} catch (NoMoreCarrotsException e ) {// DOES NOT COMPILE because eatCarrot does not //throw any exceptions and catch block is actually unreachable
System.out.print(“sad rabbit”);
}
}
public void good() throws NoMoreCarrotsException {
eatCarrot();
}
private static void eatCarrot() { }
   // note that this method does not throw any exception

Java knows that eatCarrot() can’t throw a checked exception—which means there’s no
way for the
catch block in bad() to be reached. In comparison, good() is free to declare
other exceptions.

Subclasses

Note: Subclasses when they want to override the superclass method, they can’t add checked exceptions, but overriden method can throw runtime exceptions. Also if superclass’s method throws some checked exception, overriden method in subclass actually can throw checked exception that is inherited from checked exception thrown by the superclass’s method. Sounds super difficult but I will give examples.

class CanNotHopException extends Exception { }
class Hopper {
public void hop() { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { } // DOES NOT COMPILE because    

// superclass’s method doen’t throw checked exception.
}

class Hopper {
public void hop() throws CanNotHopException { }
}
class Bunny extends Hopper {
public void hop() { }     // compiles because overriden method doesn’t throw the exception
}

class Hopper {
public void hop() throws Exception { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { }     // this is allowed because CanNOtHopException is inherited from Exception
}

class Hopper {
public void hop() { }
}

class Bunny extends Hopper {
public void hop() throws IllegalStateException { }    // compiles, because only runtime //exceptions can be added to overriden methods
}

When a class overrides a method from a  superclass or implements a method from an interface, it’s not allowed to add new checked exceptions to the method signature. For example, this code isn’t allowed:

 

Printing an Exception

There are three ways to print an exception.  You can let Java print it out, print just the message, or print where the stack trace comes from.


This example shows all three approaches:
5: public static void main(String[] args) {
6: try {
7: hop();
8: } catch (Exception e) {
9: System.out.println(e);
10: System.out.println(e.getMessage());  // this will only print “cannot hop”
11: e.printStackTrace();                                  // will show exception and line where it happens
12: }
13: }
14: private static void hop() {
15: throw new RuntimeException(“cannot hop”);
16: }
This code results in the following output:
java.lang.RuntimeException: cannot hop
cannot hop
java.lang.RuntimeException: cannot hop
at trycatch.Handling.hop(Handling.java:15)
at trycatch.Handling.main(Handling.java:7)

The stack trace is usually the most helpful one because it shows where the exception
occurred in each method that it passed through.

Exception Swallowing

Because checked exceptions require you to handle or declare them, there is a temptation
to catch them so they “go away.” But doing so can cause problems. In the following code,
there’s a problem reading in the file:

 

public static void main(String[] args) {
String textInFile = null;
try {
readInFile();
} catch (IOException e) {
// ignore exception               // since nothing happens here, exception is considered to be swallowed. good idea would be to add e.printStackTrace()
}
// imagine many lines of code here
System.out.println(textInFile.replace(” “, “”));
}
private static void readInFile() throws IOException {
throw new IOException();
}
The code results in a NullPointerException. Java doesn’t tell you anything about the
original
IOException because it was handled. Granted, it was handled poorly, but it was
handled.
When writing your own code, print out a stack trace or at least a message when catching
an exception.

 

Chapter 3 Test highlights:

 

1. Which of the following statements are true? (Choose all that apply)
A. Runtime exceptions are the same thing as checked exceptions.
B. Runtime exceptions are the same thing as unchecked exceptions.
C. You can declare only checked exceptions.
D. You can declare only unchecked exceptions.
E. You can handle only Exception subclasses.

B. Runtime exceptions are also known as unchecked exceptions. They are allowed
to be declared, but they don’t have to be. Checked exceptions must be handled or
declared. Legally, you can handle java.lang.Error subclasses, but it’s not a good idea.

5. Which of the following exceptions are thrown by the JVM? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. ExceptionInInitializerError
C. java.io.IOException
D. NullPointerException
E. NumberFormatException

A, B, D. java.io.IOException is thrown by many methods in the java.io package,
but it is always thrown programmatically. The same is true for NumberFormatException; it is thrown programmatically by the wrapper classes of java.lang. The other
three exceptions are all thrown by the JVM when the corresponding problem arises.

7. What is printed besides the stack trace caused by the NullPointerException from line 16?
1: public class DoSomething {
2: public void go() {
3: System.out.print(“A”);
4: try {
5: stop();
6: } catch (ArithmeticException e) {
7: System.out.print(“B”);
8: } finally {
9: System.out.print(“C”);
10: }
11: System.out.print(“D”);
12: }
13: public void stop() {
14: System.out.print(“E”);
15: Object x = null;
16: x.toString();
17: System.out.print(“F”);
18: }
19: public static void main(String[] args) {
20: new DoSomething().go();
21: }
22: }
A. AE
B. AEBCD
C. AEC
D. AECD
E. No output appears other than the stack trace.

C. The main() method invokes go and A is printed on line 3. The stop method is
invoked and E is printed on line 14. Line 16 throws a NullPointerException, so stop
immediately ends and line 17 doesn’t execute. The exception isn’t caught in go, so the
go method ends as well, but not before its finally block executes and C is printed on
line 9. Because main() doesn’t catch the exception, the stack trace displays and no further output occurs, so AEC was the output printed before the stack trace.

9. What is the output of the following program?
1: public class Laptop {
2: public void start() {
3: try {
4: System.out.print(“Starting up “);
5: throw new Exception();
6: } catch (Exception e) {
7: System.out.print(“Problem “);
8: System.exit(0);
9: } finally {
10: System.out.print(“Shutting down “);
11: }
12: }
13: public static void main(String[] args) {
14: new Laptop().start();
15: } }
A. Starting up
B. Starting up Problem
C. Starting up Problem Shutting down
D. Starting up Shutting down
E. The code does not compile.
F. An uncaught exception is thrown

B. The main() method invokes start on a new Laptop object. Line 4 prints Starting
up; then line 5 throws an Exception. Line 6 catches the exception, line 7 prints
Problem, and then line 8 calls System.exit, which terminates the JVM. The finally
block does not execute because the JVM is no longer running.

11. What is the output of the following program?
1: public class Cat {
2: public String name;
3: public void parseName() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: int x = Integer.parseInt(name);
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: }
12: System.out.print(“5”);
13: }
14: public static void main(String[] args) {
15: Cat leo = new Cat();
16: leo.name = “Leo”;
17: leo.parseName();
18: System.out.print(“6”);
19: }
20: }
A. 12, followed by a stack trace for a NumberFormatException
B. 124, followed by a stack trace for a NumberFormatException
C. 12456
D. 12456
E. 1256, followed by a stack trace for a NumberFormatException
F. The code does not compile.
G. An uncaught exception is thrown.

A. The parseName method is invoked on a new Cat object. Line 4 prints 1. The try
block is entered, and line 6 prints 2. Line 7 throws a NumberFormatException. It isn’t
caught, so parseName ends. main() doesn’t catch the exception either, so the program
terminates and the stack trace for the NumberFormatException is printed.

12. What is printed by the following? (Choose all that apply)
1: public class Mouse {
2: public String name;
3: public void run() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: name.toString();
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: throw e;
12: }
13: System.out.print(“5”);
14: }
15: public static void main(String[] args) {
16: Mouse jerry = new Mouse();
17: jerry.run();
18: System.out.print(“6”);
19: } }
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
G. The stack trace for a NullPointerException

A, B, D, G. The main() method invokes run on a new Mouse object. Line 4 prints 1 and
line 6 prints 2, so options A and B are correct. Line 7 throws a NullPointerException,
which causes line 8 to be skipped, so C is incorrect. The exception is caught on line 9
and line 10 prints 4, so option D is correct. Line 11 throws the exception again, which
causes run() to immediately end, so line 13 doesn’t execute and option E is incorrect.
The main() method doesn’t catch the exception either, so line 18 doesn’t execute and
option F is incorrect. The uncaught NullPointerException causes the stack trace to be
printed, so option G is correct.

13. Which of the following statements are true? (Choose all that apply)
A. You can declare a method with Exception as the return type.
B. You can declare any subclass of Error in the throws part of a method declaration.
C. You can declare any subclass of Exception in the throws part of a method
declaration.
D. You can declare any subclass of Object in the throws part of a method declaration.
E. You can declare any subclass of RuntimeException in the throws part of a method
declaration.

A, B, C, E. Classes listed in the throws part of a method declaration must extend
java.lang.Throwable. This includes Error, Exception, and RuntimeException. Arbitrary classes such as String can’t go there. Any Java type, including Exception, can
be declared as the return type. However, this will simply return the object rather than
throw an exception.

14. Which of the following can be inserted on line 8 to make this code compile? (Choose all
that apply)
7: public void ohNo() throws IOException {
8: // INSERT CODE HERE
9: }
A. System.out.println(“it’s ok”);
B. throw new Exception();
C. throw new IllegalArgumentException();
D. throw new java.io.IOException();
E. throw new RuntimeException();

A, C, D, E. A method that declares an exception isn’t required to throw one, making
option A correct. Runtime exceptions can be thrown in any method, making options
C and E correct. Option D matches the exception type declared and so is also correct.
Option B is incorrect because a broader exception is not allowed.

17. Which of the following can be inserted into Lion to make this code compile? (Choose all
that apply)
class HasSoreThroatException extends Exception {}
class TiredException extends RuntimeException {}
interface Roar {
void roar() throws HasSoreThroatException;
}
class Lion implements Roar {// INSERT CODE HERE
}
A. public void roar(){}
B. public void roar() throws Exception{}
C. public void roar() throws HasSoreThroatException{}
D. public void roar() throws IllegalArgumentException{}
E. public void roar() throws TiredException{}

A, C, D, E. The method is allowed to throw no exceptions at all, making option A correct. It is also allowed to throw runtime exceptions, making options D and E correct.
Option C is also correct since it matches the signature in the interface.

18. Which of the following are true? (Choose all that apply)
A. Checked exceptions are allowed to be handled or declared.
B. Checked exceptions are required to be handled or declared.
C. Errors are allowed to be handled or declared.
D. Errors are required to be handled or declared.
E. Runtime exceptions are allowed to be handled or declared.
F. Runtime exceptions are required to be handled or declared.

A, B, C, E. Checked exceptions are required to be handled or declared. Runtime
exceptions are allowed to be handled or declared. Errors are allowed to be handled or
declared, but this is bad practice.

19. Which of the following can be inserted in the blank to make the code compile? (Choose all
that apply)
public static void main(String[] args) {
try {
System.out.println(“work real hard”);
} catch (______ e) {
} catch (RuntimeException e) {
}
}
A. Exception
B. IOException
C. IllegalArgumentException
D. RuntimeException
E. StackOverflowError
F. None of the above.

C, E. Option C is allowed because it is a more specific type than RuntimeException.
Option E is allowed because it isn’t in the same inheritance tree as RuntimeException. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the try block doesn’t declare an IOException to be thrown. The
compiler realizes that IOException would be an unreachable catch block. Option D
is not allowed because the same exception can’t be specified in two different catch
blocks. Finally, option A is not allowed because it’s more general than RuntimeException and would make that block unreachable.

20. What does the output of the following contain? (Choose all that apply)
12: public static void main(String[] args) {
13: System.out.print(“a”);
14: try {
15: System.out.print(“b”);
16: throw new IllegalArgumentException();
17: } catch (IllegalArgumentException e) {
18: System.out.print(“c”);
19: throw new RuntimeException(“1”);
20: } catch (RuntimeException e) {
21: System.out.print(“d”);
22: throw new RuntimeException(“2”);
23: } finally {
24: System.out.print(“e”);
25: throw new RuntimeException(“3”);
26: }
27: }
A. abce
B. abde
C. An exception with the message set to “1”
D. An exception with the message set to “2”
E. An exception with the message set to “3”
F. Nothing; the code does not compile.

A, E. The code begins normally and prints a on line 13, followed by b on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also
throws an exception, that’s the one printed.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s