Programmer I Chapter 10: Exceptions Flashcards

1
Q

What will this method print?

30: public String exceptions() {
31: StringBuilder result = new StringBuilder();
32: String v = null;
33: try {
34: try {
35: result.append(“before_”);
36: v.length();
37: result.append(“after_”);
38: } catch (NullPointerException e) {
39: result.append(“catch_”);
40: throw new RuntimeException();
41: } finally {
42: result.append(“finally_”);
43: throw new Exception();
44: }
45: } catch (Exception e) {
46: result.append(“done”);
47: }
48: return result.toString();
49: }

A

before_catch_finally_done

First on line 35, “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 lines34–44. The outer catch block then sees an exception was thrown and catches it on line 45; it adds “done” to result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which of the following statements are true? (Choose all that apply.)

A. Exceptions of type RuntimeException are unchecked.
B. Exceptions of type RuntimeException are checked.
C. You can declare unchecked exceptions.
D. You can declare checked exceptions.
E. You can handle only Exception subclasses.
F. All exceptions are subclasses of Throwable

A

A, C, D, F.
Runtime exceptions are unchecked, making option A correct and option B incorrect. Both runtime and checked exceptions can be declared, although only checked exceptions must be handled or declared, making options C and D correct.Legally, you can handle java.lang.Error subclasses, which are not subclasses of Exception, but it’s not a good idea, so option E is incorrect. Finally, it is true that all exceptions are subclasses of Throwable, making option F correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which of the following pairs fill in the blanks to make this code compile? (Choose all that apply.)

6: public void ohNo(ArithmeticException ae) _______Exception {
7: if(ae==null) ______________ Exception();
8: else ______________ ae;
9: }

A. On line 6, fill in throw
B. On line 6, fill in throws
C. On line 7, fill in throw
D. On line 7, fill in throw new
E. On line 8, fill in throw
F. On line 8, fill in throw new
G. None of the above
A

B, D, E.
In a method declaration, the keyword throws is used,making option B correct and option A incorrect. To actually throw an exception, the keyword throw is used. The new keyword must be used if the exception is being created. The new keyword is not used when throwing an existing exception. For these reasons, options D and E are correct, while options C and F are incorrect. Since the code compiles with options B, D, and E, option G is incorrect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is printed by the following? (Choose all that apply.)

1: public class Mouse {
2: public String name;
3: public void findCheese() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: name.toString();
8: System.out.print(“3”);
9: } catch (NullPointerException e | ClassCastException e) {
10: System.out.print(“4”);
11: throw e;
12: }
13: System.out.print(“5”);
14: }
15: public static void main(String… tom) {
16: Mouse jerry = new Mouse();
17: jerry.findCheese();
18: } }

A. 1
B. 2
C. 3
D. 4
E. 5
F. The stack trace for a NullPointerException
G. None of the above
A

G.
When using a multi-catch block, only one variable can be declared. For this reason, line 9 does not compile and option G correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of the following statements about finally blocks are true? (Choose all that apply.)

A. A finally block is never required with a regular try statement.
B. A finally block is required when there are no catch blocks in a regular try statement.
C. A finally block is required when the program code doesn’t terminate on its own.
D. A finally block is never required with a try-with-resources statement.
E. A finally block is required when there are no catch blocks in a try-with-resources statement.
F. A finally block is required in order to make sure all resources are closed in a try-with-resources statement.
G. A finally block is executed before the resources declared in a try-with-resources statement are closed.

A

B, D.
A regular try statement is required to have a catch clause and/or finally clause. If a regular try statement does not have any catch clauses, then it must have a finally block, making option B correct and option A incorrect. Alternatively, a try-with-resources block is not required to have a catch or finally block,making option D correct and option E incorrect. Option C is incorrect, as there is no requirement a program must terminate.Option F is also incorrect. A try-with-resources statement automatically closes all declared resources. While additional resources can be created or declared in a try-with-resources statement, none are required to be closed by a finally block.Option G is also incorrect. The implicit or hidden finally block created by the JVM when a try-with-resources statement is declared is executed first, followed by any programmer-defined finally block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which exception will the following method throw?

3: public static void main(String[] other) {
4: Object obj = Integer.valueOf(3);
5: String str = (String) obj;
6: obj = null;
7: System.out.println(obj.equals(null));
8: }

A. ArrayIndexOutOfBoundsException
B. IllegalArgumentException
C. ClassCastException
D. NumberFormatException
E. NullPointerException
F. None of the above
A

C.
Line 5 tries to cast an Integer to a String. Since String does not extend Integer, this is not allowed, and a ClassCastException is thrown, making option C correct. If line 5 were removed, then the code would instead produce a NullPointerException on line 7.Since the program stops after line 5, though, line 7 is never reached

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the following method print?

11: public void tryAgain(String s) {
12: try(FileReader r = null, p = new FileReader(“”)) {
13: System.out.print(“X”);
14: throw new IllegalArgumentException();
15: } catch (Exception s) {
16: System.out.print(“A”);
17: throw new FileNotFoundException();
18: } finally {
19: System.out.print(“O”);
20: }
21: }

A. XAO
B. XOA
C. One line of this method contains a compiler error.
D. Two lines of this method contain compiler errors.
E. Three lines of this method contain compiler errors.
F. The code compiles, but a NullPointerException is thrown atruntime.
G. None of the above

A

E.
The code does not compile, so options A, B, and F are incorrect.The first compiler error is on line 12. Each resource in a try-with-resources statement must have its own data type and be separated by a semicolon (;). The fact that one of the references is declared null does not prevent compilation. Line 15 does not compile because the variable s is already declared in the method. Line 17 also does not compile. The FileNotFoundException, which inherits from IOException and Exception, is a checked exception, so it must be handled in a try/catch block or declared by the method.Because these three lines of code do not compile, option E is the correct answer. Line 14 does compile; since it is an unchecked exception, it does not need to be caught, although in this case it is caught by the catch block on line 15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What will happen if you add the following statement to a working main() method?

System.out.print(4 / 0);

A. It will not compile.
B. It will not run.
C. It will run and throw an ArithmeticException.
D. It will run and throw an IllegalArgumentException.
E. None of the above

A

C.
The compiler tests the operation for a valid type but not a valid result, so the code will still compile and run. At runtime,evaluation of the parameter takes place before passing it to the print() method, so an ArithmeticException object is raised, and option C is correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is printed by the following program?

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 n[]) {
20: new DoSomething().go();
21: }
22: }

A. AE
B. AEBCD
C. AEC
D. AECD
E. AE followed by a stack trace
F. AEBCD followed by a stack trace
G. AEC followed by a stack trace
H. A stack trace with no other output
A
G. 
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 16throws 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. For these reasons, AEC is printed followed by a stack trace for a NullPointerException, making option G correct
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the output of the following snippet, assuming a and b are both 0?

3: try {
4: System.out.print(a / b);
5: } catch (RuntimeException e) {
6: System.out.print(-1);
7: } catch (ArithmeticException e) {
8: System.out.print(0);
9: } finally {
10: System.out.print(“done”);
11: }

A. -1
B. 0
C. done-1
D. done0
E. The code does not compile.
F. An uncaught exception is thrown.
G. None of the above
A
E. 
The order of catch blocks is important because they’re checked in the order they appear after the try block. Because ArithmeticException is a child class of RuntimeException, the catch block on line 7 is unreachable (if an ArithmeticException is thrown in the try block, it will be caught on line 5). Line 7generates a compiler error because it is unreachable code, making option E correct
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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[] w) {
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.
A
B. 
The main() method invokes start on a new Laptop object. Line4 prints Starting up_, and then line 5 throws an Exception. Line 6 catches the exception. Line 7 then prints Problem_, and line 8 calls System.exit(0), which terminates the JVM. The finally block does not execute because the JVM is no longer running. For these reasons, option B is correct.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the output of the following program?

1: public class Dog {
2: public String name;
3: public void runAway() {
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 (NumberFormatException e) {
10: System.out.print(“4”);
11: }
12: }
13: public static void main(String… args) {
14: Dog webby = new Dog();
15: webby.name = “Webby”;
16: webby.runAway();
17: System.out.print(“5”);
18: } }

A. 1234
B. 1235
C. 124
D. 1245
E. The code does not compile.
F. An uncaught exception is thrown.
G. None of the above
A

D.
The run Away() method is invoked within main() on a new Dog object. Line 4 prints 1. The try block executes, and 2 is printed.Line 7 throws a NumberFormatException, so line 8 doesn’t execute.The exception is caught on line 9, and line 10 prints 4. Because the exception is handled, execution resumes normally. The run Away()method runs to completion, and line 17 executes, printing 5.That’s the end of the program, so the output is 1245, and option Dis correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the output of the following program?

1: public class Cat {
2: public String name;
3: public void knockStuffOver() {
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 loki = new Cat();
16: loki.name = “Loki”;
17: loki.knockStuffOver();
18: System.out.print(“6”);
19: } }

A. The output is 12, followed by a stack trace for a NumberFormatException.
B. The output is 124, followed by a stack trace for a NumberFormatException.
C. The output is 12456.
D. The output is 1256, followed by a stack trace for a NumberFormatException.
E. The code does not compile.
F. An uncaught exception is thrown.
G. None of the above

A
A. 
The knockStuffOver() method is invoked on a new Cat object.Line 4 prints 1. The try block is entered, and line 6 prints 2. Line 7throws a NumberFormatException. It isn’t caught, so knockStuffOver() ends. The main() method doesn’t catch the exception either, so the program terminates, and the stack trace for the NumberFormatException is printed. For these reasons,option A is correct.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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 a method with RuntimeException as the return type.
C. You can declare any subclass of Error in the throws part of a method declaration.
D. You can declare any subclass of Exception in the throws part of a method declaration.
E. You can declare any subclass of Object in the throws part of a method declaration.
F. You can declare any subclass of RuntimeException in the throws part of a method declaration.
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which of the following can be inserted on line 8 to make this code compile? (Choose all that apply.)

7: public void whatHappensNext() 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();
F. None of the above
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is printed by the following program? (Choose all that apply.)

1: public class Help {
2: public void callSuperhero() {
3: try (String raspberry = new String(“Olivia”)) {
4: System.out.print(“Q”);
5: } catch (Error e) {
6: System.out.print(“X”);
7: } finally {
8: System.out.print(“M”);
9: }
10: }
11: public static void main(String[] args) {
12: new Help().callSuperhero();
13: System.out.print(“S”);
14: } }

A. SQM
B. QXMS
C. QSM
D. QMS
E. A stack trace
F. The code does not compile because NumberFormatException is not declared or caught.
G. None of the above
A
G. 
The class does not compile because String does not implement AutoCloseable, making option G the only correct answer.
17
Q

Which of the following do not need to be handled or declared?(Choose all that apply.)

A. ArrayIndexOutOfBoundsException
B. IllegalArgumentException
C. IOException
D. Error
E. NumberFormatException
F. Any exception that extends RuntimeException
G. Any exception that extends Exception
A
A, B, D, E, F. 
Any class that extends RuntimeException or Error,including the classes themselves, is an unchecked exception,making options D and F correct. The classes ArrayIndexOutOfBoundsException, IllegalArgumentException, and NumberFormatException all extend RuntimeException, making them unchecked exceptions and options A, B, and E correct. (Sorry, you have to memorize them.) Classes that extend Exception but not RuntimeException are checked exceptions, making options C and G incorrect
18
Q

Which lines can fill in the blank to make the following code compile? (Choose all that apply.)

void rollOut() throws ClassCastException {}
public void transform(String c) {
try {
rollOut();
} catch (IllegalArgumentException | \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ ) {}
}
A. IOException a
B. Error b
C. NullPointerException c
D. RuntimeException d
E. NumberFormatException e
F. ClassCastException f
G. None of the above. The code contains a compiler error regardless of what is inserted into the blank.
A

B, F.
The try block is not capable of throwing an IOException. For this reason, declaring it in the catch block is considered unreachable code, making option A incorrect. Options B and F are correct, as both are unchecked exceptions that do not extend or inherit from IllegalArgumentException. Remember, it is not a good idea to catch Error in practice, although because it is possible, it may come up on the exam. Option C is incorrect, but not because of the data type. The variable c is declared already in the method declaration, so it cannot be used again as a local variable in the catch block. If the variable name was changed,option C would be correct. Option D is incorrect because the IllegalArgumentException inherits from RuntimeException,making the first declaration unnecessary. Similarly, option E is incorrect because NumberFormatException inherits from IllegalArgumentException, making the second declaration unnecessary. Since options B and F are correct, option G is incorrect.

19
Q

Which scenario is the best use of an exception?

A. An element is not found when searching a list.
B. An unexpected parameter is passed into a method.
C. The computer caught fire.
D. You want to loop through a list.
E. You don’t know how to code a method.

A

B.
An IllegalArgumentException is used when an unexpected parameter is passed into a method. Option A is incorrect because returning null or -1 is a common return value for searching for data. Option D is incorrect because a for loop is typically used for this scenario. Option E is incorrect because you should find out how to code the method and not leave it for the unsuspecting programmer who calls your method. Option C is incorrect because you should run!

20
Q

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 int roar() throws RuntimeException {}
C. public void roar() throws Exception {}
D. public void roar() throws HasSoreThroatException {}
E. public void roar() throws IllegalArgumentException {}
F. public void roar() throws TiredException {}

A

A, D, E, F.
An overridden method is allowed to throw no exceptions at all, making option A correct. It is also allowed to throw new unchecked exceptions, making options E and F correct.Option D is also correct since it matches the signature in the interface. Option B is incorrect because it has the wrong return type for the method signature. Option C is incorrect because an overridden method cannot throw new or broader checked exceptions

21
Q

Which of the following are true? (Choose all that apply.)

A. Checked exceptions are allowed, but not required, to be handled or declared.
B. Checked exceptions are required to be handled or declared.
C. Errors are allowed, but not required, to be handled or declared.
D. Errors are required to be handled or declared.
E. Unchecked exceptions are allowed, but not required, to be handled or declared.
F. Unchecked exceptions are required to be handled or declared

A

B, C, E.
Checked exceptions are required to be handled or declared, making option B correct. Unchecked exceptions include both runtime exceptions and errors, both of which may be handled or declared but are not required to be making options C and E correct. Note that handling or declaring Error is a bad practice

22
Q

Which of the following pairs fill in the blanks to make this code compile? (Choose all that apply.)

6: public void ohNo(IOException ie) ______ Exception {
7: ________________ FileNotFoundException();
8: ________________ ie;
9: }

A. On line 6, fill in throw
B. On line 6, fill in throws
C. On line 7, fill in throw
D. On line 7, fill in throw new
E. On line 8, fill in throw
F. On line 8, fill in throw new
G. None of the above
A

G.
The code does not compile, regardless of what is inserted into the blanks. You cannot add a statement after a line that throws an exception. For this reason, line 8 is unreachable after the exception is thrown on line 7, making option G correct

23
Q

Which of the following can be inserted in the blank to make the code compile? (Choose all that apply.)

public void dontFail() {
try {
System.out.println("work real hard");
} catch (\_\_\_\_\_\_\_\_\_\_\_\_\_ e) {} 
catch (RuntimeException e) {}
}
A. var
B. Exception
C. IOException
D. IllegalArgumentException
E. RuntimeException
F. StackOverflowError
G. None of the above
A

D, F.
A var is not allowed in a catch block since it doesn’t indicate the exception being caught, making option A incorrect. With multiple catch blocks, the exceptions must be ordered from more specific to broader, or be in an unrelated inheritance tree. For these reasons, options D and F are correct, respectively. Alternatively, if a broad exception is listed before a specific exception or the same exception is listed twice, it becomes unreachable. For these reasons, options B and E are incorrect, respectively. Finally, option C is incorrect 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

24
Q

What does the output of the following method 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

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

25
Q

What does the following class output?

1: public class MoreHelp {
2: class Sidekick implements AutoCloseable {
3: protected String n;
4: public Sidekick(String n) { this.n = n; }
5: public void close() { System.out.print(“L”); }
6: }
7: public void requiresAssistance() {
8: try (Sidekick is = new Sidekick(“Adeline”)) {
9: System.out.print(“O”);
10: } finally {
11: System.out.print(“K”);
12: }
13: }
14: public static void main(String… league) {
15: new MoreHelp().requiresAssistance();
16: System.out.print(“I”);
17: } }

A. LOKI
B. OKLI
C. OLKI
D. OKIL
E. The output cannot be determined until runtime.
F. Nothing; the code does not compile.
G. None of the above
A

C.
The code compiles and runs without issue, so options E and Fare incorrect. Since Sidekick correctly implements AutoCloseable, it can be used in a try-with-resources statement. The first value printed is O on line 9. For this question, you need to remember that a try-with-resources statement executes the resource’s close() method before a programmer-defined finally block. For this reason, L is printed on line 5. Next, the finally block is expected, and K is printed. The requires Assistance() method ends, and the main() method prints I on line 16. The combined output is OLKI, making option C the correct answer.

26
Q

What does the following code snippet return, assuming a and bare both 1?

13: try {
14: return a / b;
15: } catch (ClassCastException e) {
16: return 10;
17: } catch (RuntimeException e) {
18: return 20;
19: } finally {
20: return 30;
21: }

A. 1
B. 10
C. 20
D. 30
E. The code does not compile.
F. An uncaught exception is thrown.
G. None of the above
A
D. 
The code compiles without issue since ClassCastException is a subclass of RuntimeException and it is properly listed first, so option E is incorrect. Line 14 executes dividing 1 by itself,resulting in a value of 1. Since no exception is thrown, options Band C are incorrect. The value returned is on track to be 1, but the finally block interrupts the flow, causing the method to return 30instead and making option D correct. Remember, barring use of System.exit(), a finally block is always executed if the try statement is entered, even if no exception is thrown or a return statement is used