chapter 6

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

The try block is also referred as ...

//The try block is also referred to //as protected code

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.

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

10. What is the output of the following program? 1: public class Dog { 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 (NumberFormatException e) { 10: System.out.print("4"); 11: } 12: } 13: public static void main(String[] args) { 14: Dog leroy = new Dog(); 15: leroy.name = "Leroy"; 16: leroy.parseName(); 17: System.out.print("5"); 18: } } A. 12 B. 1234 C. 1235 D. 124 E. 1245 F. The code does not compile. G. An uncaught exception is thrown.

10. E. The parseName 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. parseName runs to completion, and line 17 executes, printing 5. That's the end of the program, so the output is 1245.

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.

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

12. 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. Chapter 6: Exceptions 351

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.

13. 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();

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

15. Which of the following are unchecked exceptions? (Choose all that apply) A. ArrayIndexOutOfBoundsException B. IllegalArgumentException C. IOException D. NumberFormatException E. Any exception that extends RuntimeException F. Any exception that extends Exception

15. A, B, D, E. ArrayIndexOutOfBoundsException, IllegalArgumentException, and NumberFormatException are runtime exceptions. Sorry, you have to memorize them. Any class that extends RuntimeException is a runtime (unchecked) exception. Classes that extend Exception but not RuntimeException are checked exceptions.

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

16. B. 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 this scenario. 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!

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

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

18. 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 allthat 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.

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

2. Which of the following pairs fill in the blanks to make this code compile? (Choose all that apply) 7: public void ohNo() _____ Exception { 8: _____________ Exception(); 9: } A. On line 7, fill in throw B. On line 7, fill in throws C. On line 8, fill in throw D. On line 8, fill in throw new E. On line 8, fill in throws F. On line 8, fill in throws new

2. B, D. In a method declaration, the keyword throws is used. To actually throw an exception, the keyword throw is used and a new exception is created.

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.

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

3. When are you required to use a finally block in a regular try statement (not a try-with resources)? A. Never. B. When the program code doesn't terminate on its own. C. When there are no catch blocks in a try statement. D. When there is exactly one catch block in a try statement. E. When there are two or more catch blocks in a try statement.

3. C. A try statement is required to have a catch clause and/or finally clause. If it goes the catch route, it is allowed to have multiple catch clauses.

4. Which exception will the following throw? Object obj = new Integer(3); String str = (String) obj; System.out.println(str); A. ArrayIndexOutOfBoundsException B. ClassCastException C. IllegalArgumentException D. NumberFormatException E. None of the above.

4. B. The second line tries to cast an Integer to a String. Since String does not extend Integer, this is not allowed and a ClassCastException is thrown. .

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

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

6. What will happen if you add the statement System.out.println(5 / 0); to a working main() method? 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.

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

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.

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

8. What is the output of the following snippet, assuming a and b are both 0? 3: try { 4: return a / b; 5: } catch (RuntimeException e) { 6: return -1; 7: } catch (ArithmeticException e) { 8: return 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.

8. 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 Runtime- Exception, the catch block on line 7 is unreachable. (If an ArithmeticException is thrown in try try block, it will be caught on line 5.) Line 7 generates a compiler error because it is unreachable code.

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

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

runtime exception

A runtime exception is defined as the RuntimeException class and its subclasses. Runtime exceptions tend to be unexpected but not necessarily fatal

Errors extend the _______ They are thrown by the JVM and should ______________

Error class. not be handled or declared

Checked exceptions have ________ in their hierarchy but not ____________. They must be _____________

Exception RuntimeException handled or declared.

A checked exception includes ___________ and all __________ that do not extend _____________. Checked exceptions tend to be more ________

Exception subclasses RuntimeException. anticipated

what does this code do 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.

Type Error How to recognize Okay for program to catch? Is program required to handle or declare?

How to recognize Subclass of Error Okay for program to catch? No Is program required to handle or declare? No

Type Checked exception How to recognize Okay for program to catch? Is program required to handle or declare?

How to recognize Subclass of Exception but not subclass of RuntimeException Okay for program to catch? Yes Is program required to handle or declare? Yes

Type Runtime exception How to recognize Okay for program to catch? Is program required to handle or declare?

How to recognize Subclass of RuntimeException Okay for program to catch? yes Is program required to handle or declare? no

what happens in this code 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"); } }

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.

what happens in this code 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 specific ExhibitClosedForLunch exception is thrown, the first catch block runs. If not, Java checks if the superclass ExhibitClosed exception is thrown and catches it.

why does this code not 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.

try statement

Java uses a try statement to separate the logic that might throw an exception from the logic to handle that exception.

exception

Java's way of saying, "I give up. I don't know what to do right now. You deal with it." When you write a method, you can either deal with the exception or make it the calling code's problem.

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.

what happens in this code 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.

why does this code 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 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.

what does this code do 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.

why does this code not compile 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"); }

why does this code not compile try {// DOES NOT COMPILE fall(); }

This code doesn't compile because the try block doesn't have anything after it.

what does this do String[] animals = new String[0]; System.out.println(animals[0]);

This code throws an ArrayIndexOutOfBoundsException.

why does this code not compile 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 specifi c 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

NoClassDefFoundError

Thrown by the JVM when a class that the code uses is available at compile time but not runtime

StackOverflowError

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

ExceptionInInitializerError

Thrown by the JVM when a static initializer throws an exception and doesn't handle it

ClassCastException

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

ArrayIndexOutOfBoundsException

Thrown by the JVM when code uses an illegal index to access an array

NullPointerException

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

IllegalArgumentException

Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument

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

Subclasses

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.

finally Block

a finally clause regardless of whether an exception is thrown.

catch

exception_type identifier ) { //exception handler

Runtime exceptions are also known as ......

unchecked exceptions.


Kaugnay na mga set ng pag-aaral

Chapter 4: Types of Life Insurance Policies Quiz

View Set

MKTG-375 Connect Quizzes McNeese

View Set

MS Chapter 55 Sexually Transmitted Infections (PQR)

View Set