Chapter 7 - Exception Handling

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

Select the incorrect statement(s): a) Exceptions enable a developer to define the programming logic separate from the exception- handling code. b) Exception handling speeds up execution of the code. c) Exception handing is used to define code that should execute when a piece of code throws an exception. d) Code that handles all the checked exceptions can still throw unchecked exceptions.

Answer: b Explanation: No direct relationship exists between exception handling and improved execution of code. Code that handles all the checked exceptions can throw unchecked exceptions and vice versa.

What is the output of the following code? class EJavaBase { void myMethod() throws ExceptionInInitializerError { System.out.println("Base"); } } class EJavaDerived extends EJavaBase { void myMethod() throws RuntimeException { System.out.println("Derived"); } } class EJava3 { public static void main(String args[]) { EJavaBase obj = new EJavaDerived(); obj.myMethod(); } } a) Base b) Derived c) Derived Base d) Base Derived e) Compilation error

Answer: b Explanation: The rule that if a base class method doesn't throw an exception, an overriding method in the derived class can't throw a exception applies only to checked exceptions. It doesn't apply to runtime (unchecked) exceptions or errors. A base or overridden method is free to throw any Error or runtime exception.

Select the correct option(s): a) You cannot handle runtime exceptions. b) You should not handle errors. c) If a method throws a checked exception, it must be either handled by the method or specified in its throws clause. d) If a method throws a runtime exception, it may include the exception in its throws clause. e) Runtime exceptions are checked exceptions.

Answer: b, c, d Explanation: Option (a) is incorrect. You can handle runtime exceptions the way you can handle a checked exception in your code: using a try-catch block. Option (b) is correct. You shouldn't try to handle errors in your code. Or, to put it another way, you can't do much when an error is thrown by your code. Instead of trying to handle errors in your code, you should resolve the code that results in these errors. For example, StackOverflowError is an error that will be thrown by your code if your code executes a method recursively without any exit condition. This repetition will consume all the space on the stack and result in a StackOverflowError. Option (c) is correct. If you fail to implement either of these options, your code won't compile. Option (d) is correct. It isn't mandatory for runtime exceptions to be included in a method's throws clause. Usually this inclusion is unnecessary, but if you do include it, your code will execute without any issues. Option (e) is incorrect. Runtime exception and all its subclasses are not checked exceptions.

What is the output of the following code? class TryFinally { int tryAgain() { int a = 10; try { ++a; } finally { a++; } return a; } public static void main(String args[]) { System.out.println(new TryFinally().tryAgain()); } } a) 10 b) 11 c) 12 d) Compilation error e) Runtime exception

Answer: c Explanation: The try block executes, incrementing the value of variable a to 11. This step is followed by execution of the finally block, which also increments the value of variable a by 1, to 12. The method tryAgain returns the value 12, which is printed by the method main. There are no compilation issues with the code. A try block can be followed by a finally block, without any catch blocks. Even though the try block doesn't throw any exceptions, it compiles successfully. The following is an example of a try-catch block that won't compile because it tries to catch a checked exception that's never thrown by the try block: try { ++a; } catch (java.io.FileNotFoundException e) { }

Select the incorrect statement(s): a) java.lang.Throwable is the base class of all type of exceptions. b) If a class is a subclass of java.lang.Exception, it may or may not be a checked exception. c) Error is an unchecked exception. d) Error and checked exceptions need not be part of a method signature.

Answer: c, d Explanation: Option (a) is a true statement. A checked exception is a subclass of java.lang.Exception, and a runtime exception is a subclass of java.lang.RuntimeException. java.lang.RuntimeException is a subclass of java.lang.Exception, and java.lang.Exception is a subclass of java.lang.Throwable. Hence, all the exceptions are subclasses of java.lang.Throwable. Option (b) is also a true statement. Unchecked exceptions are subclasses of class java.lang.RuntimeException, which itself is a subclass of java.lang.Exception. Hence, a class can be a subclass of class java.lang.Exception and either a checked or an unchecked exception. Option (c) is a false statement. Error is not an exception. It does not subclass java.lang.Exception. Option (d) is also a false statement. Error need not be part of a method signature, but checked exceptions must be a part of the method signatures.

Which of the following statements are true? a) A user-defined class may not throw an IllegalStateException. It must be thrown only by Java API classes. b) System.out.println will throw NullPointerException if an uninitialized instance variable of type String is passed to it to print its value. c) NumberFormatException is thrown by multiple methods from the Java API when invalid numbers are passed on as Strings to be converted to the specified number format. d) ExceptionInInitializerError may be thrown by the JVM when a static initializer in your code throws a NullPointerException.

Answer: c, d Option (a) is incorrect. A user-defined class can throw any exception from the Java API. Option (b) is incorrect. An uninitialized instance variable of type String will be assigned a default value of null. When you pass this variable to System.out.println to print it, it will print null. If you try to access any member (variable or method) of this null object, then NullPointerException will be thrown.

What is the output of the following code? class EJava4 { void foo() { try { String s = null; System.out.println("1"); try { System.out.println(s.length()); } catch (NullPointerException e) { System.out.println("inner"); } System.out.println("2"); } catch (NullPointerException e) { System.out.println("outer"); } } public static void main(String args[]) { EJava4 obj = new EJava4(); obj.foo(); } } a) 1 inner 2 outer b) 1 outer c) 1 inner d) 1 inner 2

Answer: d Explanation: First of all, nested try-catch statements don't throw compilation errors. Because the variable s hasn't been initialized, an attempt to access its method length() will throw a NullPointerException. The inner try-catch block handles this exception and prints inner. The control then moves on to complete the remaining code in the outer try-catch block, printing 2. Because the NullPointer-Exception was already handled in the inner try-catch block, it's not handled in the outer try-catch block.

Examine the following code and select the correct option(s): class EJavaGuruExcep2 { public static void main(String args[]) { EJavaGuruExcep2 var = new EJavaGuruExcep2(); var.printArrValues(args); } void printArrValues(String[] arr) { try { System.out.println(arr[0] + ":" + arr[1]); } catch (NullPointerException e) { System.out.println("NullPointerException"); } catch (IndexOutOfBoundsException e) { System.out.println("IndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException"); } } } a) If the class EJavaGuruExcep2 is executed using the following command, it prints NullPointerException: javaEJavaGuruExcep2 b) If the class EJavaGuruExcep2 is executed using the following command, it prints IndexOutOfBoundsException: javaEJavaGuruExcep2 c) If the class EJavaGuruExcep2 is executed using the following command, it prints ArrayIndexOutOfBoundsException: javaEJavaGuruExcep2one d) The code will fail to compile.

Answer: d Explanation: The key to answering this question is to be aware of the following two facts: ■ Exceptions are classes. If an exception's base class is used in a catch block, it can catch all the exceptions of its derived class. If you try to catch an exception from its derived class afterward, the code won't compile. ■ ArrayIndexOutOfBoundsException is a derived class of IndexOutOfBounds-Exception. The rest of the points try to trick you into believing that the question is based on the arguments passed to a main method.

What is the output of the following code: class Course { String courseName; Course() { Course c = new Course(); c.courseName = "Oracle"; } } class EJavaGuruPrivate2 { public static void main(String args[]) { Course c = new Course(); c.courseName = "Java"; System.out.println(c.courseName); } } a) The code will print Java. b) The code will print Oracle. c) The code will not compile. d) The code will throw an exception or an error at runtime.

Answer: d Explanation: This class will throw StackOverflowError at runtime. The easiest way to look for a StackOverflowError is to locate recursive method calls. In the question's code, the constructor of the class Course creates an object of the class Course, which will call the constructor again. Hence, this becomes a recursive call and ends up throwing StackOverflowError at runtime. (As you know, an exception or an error can be thrown only at runtime, not compile time.)

What is the output of the following code? class EJava { void method() { try { guru(); return; } finally { System.out.println("finally 1"); } } void guru() { System.out.println("guru"); throw new StackOverflowError(); } public static void main(String args[]) { EJava var = new EJava(); var.method(); } } a) guru finally 1 b) guru finally 1 Exception in thread "main" java.lang.StackOverflowError c) guru Exception in thread "main" java.lang.StackOverflowError d) guru e) The code fails to compile.

Q7-4. Answer: b Explanation: No compilation errors exist with the code. The method guru throws StackOverflowError, which is not a checked exception. Even though your code should not throw an error, it is possible syntactically. Your code will compile successfully. The call to the method guru is immediately followed by the keyword return, which is supposed to end the execution of the method method. But the call to guru is placed within a try-catch block, with a finally block. Because guru doesn't handle the error StackOverflowError itself, the control looks for the exception handler in the method method. This calling method doesn't handle this error, but defines a finally block. The control then executes the finally block. Because the code can't find an appropriate handler to handle this error, it propagates to the JVM, which abruptly halts the code.


Kaugnay na mga set ng pag-aaral

Chapter 5; Sensation and Perception

View Set

Chapter 4: Carbohydrates: Sugars, Starches and Fibers

View Set

Sherman- Spinal Biodynamics 2- QUIZZES

View Set

Ranking Task: Luminosity, Distance and the Apparent Brightness of Stars

View Set

1-4, 6, 18, 24, 31. Health Promotion, Wellness, Disease Prevention & Religion

View Set