Java OCP Part 6. Exception and Assertions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

B and F are correct. The multi-catch block may not contain exception types that are in the same hierarchy. Since Rain is a superclass of Thunderstorm, having Thunderstorm is not allowed (and is redundant). Catching the superclass Rain or its superclass Exception has the same effect without the need for the multi-catch. A, C, D, and E are incorrect. A and C are incorrect because of the above. D and E are incorrect both because of the subclass/superclass relationship and because of incorrect syntax.

1. public class Party { 2. static class Rain extends Exception{} 3. static class Thunderstorm extends Rain{} 4. public void eat() { 5. try { 6. bbq(); 7. } catch(Rain | Thunderstorm e) { 8. } } 9. private void bbq() throws Rain, Thunderstorm { } } // Which are true? (Choose all that apply.) A. Compilation succeeds B. Compilation will succeed when line 7 is changed to }catch(Rain e) { C. Compilation will succeed when line 7 is changed to }catch(Thunderstorm e) D. Compilation will succeed when line 7 is changed to }catch(Rain e | Thunderstorm e){ E. Compilation will succeed when line 7 is changed to }catch(Rain e1 | Thunderstorm e2){ F. Compilation will succeed when line 7 is changed to }catch(Exception e){

A. The program compiles without issue, so Option D is incorrect. The narrower SpellingException and NullPointerException, which inherit from Exception, are correctly presented in the first catch block, with the broader Exception being in the second catch block. The if-then statement evaluates to true, and a new SpellingException instance is created, but it is not thrown because it is missing the 'throw' keyword. For this reason, the try block ends without any of the catch blocks being executed. The finally block is then called, making it the only section of code in the program that prints a line of text. For this reason, Option A is the correct answer.

1: class SpellingException extends RuntimeException{} 2: public final static void main(String... participants) { 3: try { 4: if( !"cat".equals("kat") ) { *new SpellingException();* } 5: } catch (SpellingException | NullPointerException e) { 6: System.out.println("Spelling problem!"); 7: } catch (Exception e) { 8: System.out.println("Unknown Problem!"); 9: } finally { 10 System.out.println("Done!"); } } } How many lines of text does the program print? A. One B. Two C. Three D. The code does not compile.

A,D

Application run with assertion is enabled. Which of the following prints OhNo when the number is negative?(Choose all.) A. assert n > 0: "OhNo"; B. assert n > 0, "OhNo"; C. assert n > 0 ("OhNo"); D. assert(n > 0): "OhNo"; E. assert(n > 0, "OhNo"); F. Nothing will be printed in any case.

7 The Teacher class, including all five assert statements, compiles without issue, making Option F incorrect. The first three assert statements on lines 4, 5, and 6 evaluate to true, not triggering any exceptions, with choices updated to 11 after the first assertion is executed. Lines 4 and 7 demonstrate the very bad practice of modifying data in an assertion statement, which can trigger side effects. Regardless of whether an assertion error is thrown, turning on/off assertions potentially changes the value returned by checkClasswork(). At line 7, the assertion statement 12==11 evaluates to false, triggering an AssertionError and making Option D the correct answer. The main() method catches and rethrows the AssertionError. Like writing assertion statements that include side effects, catching Error is also considered a bad practice. Note that line 8 also would trigger an AssertionError, but it is never reached due to the exception on line 7.

Assuming assertions enabled, the method invoked with value choices=10, which is the first line to throw an exception at runtime? 3: public int checkClasswork(int choices) { 4: assert choices++==10 : 1; 5: assert true!=false : new StringBuilder("Answer2"); 6: assert(null==null) : new Object(); 7: assert ++choices==11 : "Answer4"; 8: assert 2==3 : ""; 9: return choices; 10: }

D. The optional second parameter of an assert statement, when used, must return a value. The second assert statement uses System.out.print() as its second parameter,which has a return type of void. For this reason, the code does not compile, making Option D the correct answer. Other than this one line, the rest of the class compiles without issue.

Assuming the following application is executed with assertions enabled, what is the result? public class DataIntegrity { private int score; public DataIntegrity() { super(); DataIntegrity.this.score = 5; } public static void main(String[] books) { final DataIntegrity johnny5 = new DataIntegrity(); assert(johnny5.score>2) : johnny5.score++; assert johnny5.score>=5 : System.out.print("No input"); System.out.print("Made it!"); } } A. An AssertionError is thrown with a message of 5. B. An AssertionError is thrown with a message of No input . C. Made it! is printed. D. The code does not compile.

B,C,D,E,F Option (a) is incorrect. For the longer form of the assert statement that uses two expressions, you can't enclose both expressions within a single parentheses. Options (b) and (c) are correct. It's optional to include the individual expressions used in the longer form within a single parentheses. Options (d) and (e) are correct. The shorter form of the assert statement uses only one expression, which might or might not be included within parentheses. Option (f) is correct. The semicolon placed after the condition s=="assert"delimits the assert statement, and the statement following the semicolon is treated as a separate statement. Option (g) is incorrect because the first expression in an assert statement must return a boolean value. In this code, the first expression returns an object of class String. Option (h) is incorrect because the second expression in an assert statement must return a value of any type. In this code, the return type of method println() isvoid.

Given String s = "assert"; which of the following code options will compile successfully? (Choose all that apply.) A. assert(s == null : s = new String()); B. assert s == null : s = new String(); C. assert(s == null) : s = new String(); D. assert(s.equals("assert")); E. assert s.equals("assert"); F. assert s == "assert" *;* s.replace('a', 'z'); G. assert s = new String("Assert") : s.toString(); H. assert s == new String("Assert") : System.out.println(s);

B. The code does not compile, so Option E is incorrect. The first compilation error is in the try-with-resources declaration. There are two resources being declared, which is allowed, but they are separated by a comma (,) instead of a semicolon (;). The second compilation problem is that the order of exceptions in the two catch blocks are reversed. Since Exception will catch all StungException instances, the second catch block is unreachable. For these two reasons, Option B is the correct answer.

Given the following class, how many lines contain compilation errors? class StungException extends Exception {} class Suit implements Closeable { public void close() throws IOException {} } public class BeeCatcher { public static void main(String... bees) { try (Suit s = new Suit()*,* Suit t = new Suit()) { throw new StungException(); } catch (Exception e) { } catch (StungException e) { } finally { } } } A. One B. Two C. Three D. Four E. None. The code compiles as is.

D. The first compilation error is that class Shelf does not implement AutoCloseable, meaning a try-with-resources statement cannot be used. Even though Shelf does implement Closing, an interface that uses the same abstract method signature as AutoCloseable, the JVM requires AutoCloseable be implemented to use try-with-resources. The second compilation problem is that 'throws' is used instead of 'throw' inside the try block. Remember that 'throws' is only used in method signatures. The third compilation issue is that the order of exceptions in the two catch blocks are reversed. Since Exception will catch all IllegalArgumentException instances, the second catch block is unreachable. The final compilation error is that the shelf variable is used in the finally block, which is out of scope. Remember that the scope of try-with-resources variables ends when the try statement is complete.

Given the following class, how many lines contain compilation errors? interface Closing { void close() throws Exception; } class Shelf implements Closing { public void close() throws Exception {} } public class Step { static { try (Shelf shelf = new Shelf()) { throws new IllegalArgumentException(); } catch (Exception e) { } catch (IllegalArgumentException e) { } finally { shelf.close(); } } } A. None B. Two C. Three D. Four

B. Option A does not compile because the assignment (age=2) has a value of int, not boolean, which is required for an assert statement. Option B compiles without issue and is the correct answer. Even though 'Error' and 10 are different data types, String and int respectively, the second assert parameter only needs to be a value, so both are allowed. Option C does not compile because the usage of the lambda expression does not match a functional interface. Option D is incorrect because a 'return' statement is not allowed in the second expression of an assert statement

Given the following two variables, which assertion statement compiles successfully? int age = 22; final String name = "Josephine"; A. assert (age=2); B. assert age!=age : (1<age ? "Error" : 10); C. assert name.equals("") : () -> "Oops"; D. assert name.length()<(long)age : return "Mistake";

D. The Exception class contains multiple constructors, including one that takes Throwable, one that takes String, and a no-argument constructor. The first WhaleSharkException constructor compiles, using the Exception constructor that takesa String. The second WhaleSharkException constructor also compiles. The two statements, super() and new Exception(), actually call the same constructor in theException class, one after another. The last WhaleSharkException compiles with the compiler inserting the default no-argument constructor super(), because it exists inthe Exception class. For these reasons, all of the constructors compile, and Option D is the correct answer.

How many constructors in WhaleSharkException compile in the following class? public class WhaleSharkException extends Exception { public WhaleSharkException() { super("Friendly shark!"); } // 1 public WhaleSharkException(String message) { super( new Exception( new WhaleSharkException() ) ); } //2 public WhaleSharkException(Exception cause) { } //3 } A. None B. One C. Two D. Three

D. In Java, assert is a keyword, meaning it cannot be used as a variable, class, or method name. For this reason, line 5 does not compile. Line 6 also does not compile because the assert statement is not a method and does not support parentheses around both expressions.

What is the result of executing the following application with assertions enabled? 3: public static void main(String[] bricks) { 4: int flakes = 10; 5: double *assert* = 7.0; 6: assert (true :""); 7: assert flakes++>5; 8: } } A. It throws an AssertionError at runtime. B. It prints nothing at runtime. C. Exactly one line of code does not compile. D. Two lines of code do not compile.

B. The code compiles without issue, making Option E incorrect. Option A is incorrect because it disables all assertions, which is the default JVM behavior. Option B is the correct answer. It disables assertions everywhere but enables them within the Watch class, triggering an AssertionError at runtime within the checkHour() method. OptionC is incorrect because it enables assertions everywhere but disables them within the Watch class. Option D is also incorrect because -enableassert is not a valid JVM flag. The only valid flags to enable assertions are -ea and -enableassert*ions*

Which command causes the following class to throw an AssertionError at runtime? public class Watch { private static final short DEFAULT_HOUR = 12; private Watch() { super(); } int checkHour() { assert DEFAULT_HOUR > 12; return DEFAULT_HOUR; } public static void main(String... ticks) { new Watch().checkHour(); } } A. java -da Watch B. java -ea:Watch -da Watch C. java -ea -da:Watch Watch D. java -enableassert Watch

A, C. First off, the try block is capable of throwing two checked exceptions, MissingMoneyException and MissingFoodException. The catch block uses the Exception class to handle this, since both have Exception as a supertype. It then re-throws the Exception. For this reason, Exception would be appropriate in the blank,making the first statement correct. The compiler is also smart enough to know that there are only two possible subclasses of Exception that can actually be thrown in the main() method, so declaring MissingMoneyException and MissingFoodExceptiontogether also allows the code to compile, making the third statement correct. The second statement, only inserting MissingMoneyException, would not allow the code to compile because the main() method could throw a checked MissingFoodException that was not handled.

Which exception classes, when inserted into the blank in the Problems class, allow the code to compile? (Choose all that apply) class MissingMoneyException extends Exception {} class MissingFoodException extends Exception {} public class Problems { public void doIHaveAProblem() throws MissingMoneyException, MissingFoodException { System.out.println("No problems"); } public static void main(String[] lots) *throws ________________*{ try { final Problems p = new Problems(); p.doIHaveAProblem(); } catch (Exception e) { throw e; } } } A. Exception B. MissingMoneyException C. MissingMoneyException, MissingFoodException D. Nothing. Code compile as is.

D

Which of the following CANNOT fill in the blank? (Choose all.) public void read() throws SQLException { try { readFromDatabase(); } catch (_________________ e) { throw e; } } private void readFromDatabase() throws SQLException { } A. Exception B. RuntimeException C. SQLException D. SQLException | IOException E. SQLException | RuntimeException

B,D,E

Which of the following are runtime exceptions? (Choose all that apply.) A. Exception B. IllegalStateException C. IOException D. MissingResourceException E. DateTimeParseException F. SQLException

A, D, E. Any class that inherits from RuntimeException or Error is unchecked, while any class that does not is unchecked and must be declared or handled. AssertionError inherits from Error, while IllegalArgumentException and MissingResourceException inherit from RuntimeException. The remaining classes—NotSerializableException, SQLException, and ParseException—each inherit Exception but not RuntimeException, making Options A, D, and E the correct answers

Which of the following classes are checked exception? A. java.io.NotSerializableException B. java.lang.AssertionError C. java.lang.IllegalArgumentException D. java.sql.SQLException E. java.text.ParseException F. java.util.MissingResourceException

D. Only one of the classes, MissingResourceException, inherits from the unchecked RuntimeException class, making Option D the correct answer. In fact, IOException and SQLException extend the checked Exception class directly. The NotSerializableException is also checked, since it is a subclass of IOException via ObjectStreamException

Which of the following classes is an unchecked exception? A. java.io.IOExcepti on B. java.io.NotSerializableException C. java.sql.SQLException D. java.util.MissingResourceException

C,D. Options (a) and (b) are incorrect because assertions must not be used tocheck method arguments for nonprivate methods. Nonprivate methods can be calledby objects of other classes, and you can't validate their method arguments by usingassertions. Assertions can be disabled at runtime, so they aren't the right option to val-idate method arguments to public methods. You should throw exceptions in this case.For example, when you come across invalid values that are passed to a nonprivatemethod, you can throw an IllegalArgumentException

Which of the following options show appropriate usage of assertions? (Choose all that apply.) // *INSERT CODE HERE* assert (b != 0) : "Can't divide with zero"; return (a/b); } A. public float divide(int a, int b) { B. public static float divide(int a, int b) { C. private static float divide(int a, int b) { D. private float divide(int a, int b) {

A,C,E The code will print close, if class C implements the java.lang.AutoCloseable interface or any of its subinterfaces. Options (a) and (c) are correct,because Carton implements the interface java.lang.AutoCloseable itself. Option (b) is incorrect. The Closeable interface that extends the java.lang.AutoCloseable interface is defined in the java.io package. Option (d) is incorrect. The Java API doesn't define any interface with the name ImplicitCloseable in the java.lang package. Option (e) is correct because java.io.Closeable is a subinterface of java.lang.AutoCloseable.

Which of the options, when inserted at *L1* , will print close ? (Choose al) *L1* public void close() { System.out.println("close"); } } class EJavaFactory2 { public static void main(String... args) { try ( C c = new C() ) {} } } A. class C implements AutoCloseable { B. class C implements java.lang.Closeable { C. class C implements java.lang.AutoCloseable { D. class C implements ImplicitCloseable { E. class C implements java.io.Closeable {

C. Closeable extends AutoCloseable, making Option A incorrect. The difference between the two is that the close() method in AutoCloseable throws Exception, while the close() method in Closeable throws IOException, making Option D incorrect. Since IOException is a subclass of Exception, both close()methods can throw an IOException, making Option B incorrect. On the other hand, Exception is not a subclass of IOException. For this reason, the close() method in a class that implements Closeable cannot throw an instance of the Exception class, because it is an invalid override using a broader exception type, making Option C the correct answer.

Which statement about Closeable and AutoCloseable is true? A. AutoCloseable extends Closeable . B. The close() method in a class that implements AutoCloseable cannot throw an IOException . C. The close() method in a class that implements Closeable cannot throw an Exception . D. There is no difference; one was added for backward compatibility.

B, F. The LackOfInformationException class does not compile, making Option A incorrect. The compiler inserts the default no-argument constructor into InformationException since the class does not explicitly define any. Since LackOfInformationException extends InformationException, the only constructor available in the parent class is the no-argument call to super(). For this reason, the constructor defined at line t1 does not compile because it calls a nonexistent parent constructor that takes a String value, and Option B is one of the correct answers. The other two constructors at lines t2 and t3 compile without issue, making Options C and D incorrect. Option E is also incorrect. The getMessage() method is inherited, so applying the @Override annotation is allowed by the compiler. Option F is the other correct answer. The LackOfInformationException is a checked exception because it inherits Exception but not RuntimeException.

Which statements about the following class are correct? (Choose two.) class InformationException extends Exception {} public class LackOfInformationException extends InformationException { /*t1*/ public LackOfInformationException() { super(""); } /*t2*/ public LackOfInformationException(String s) { this(new Exception(s) ); } /*t3*/ public LackOfInformationException(Exception c) { super(); } @Override public String getMessage() { return "lackOf"; } } A. LackOfInformationException compiles without issue. B. The constructor declared at line t1 does not compile. C. The constructor declared at line t2 does not compile. D. The constructor declared at line t3 does not compile. E. The getMessage() method does not compile because of the @Override annotation. F. LackOfInformationException is a checked exception

A,C. First off, a class must inherit from RuntimeException or Error to be considered an unchecked exception. Dopey and Grumpy both are subclasses of Exception, but not RuntimeException, making them both checked exceptions. Since IOException is a checked exception, the subclass Happy is also a checked exception. Sleepy extends IllegalStateException, which is an unchecked exception that extends RuntimeException. Finally, Sneezy extends Throwable, which does not inherit RuntimeException or Error, making it a checked exception. Therefore, there are a total of four checked exceptions and one unchecked exception within the classes listed here. Also there are no compilation errors in any of the class declarations.

Which statements about the following classes are true? (Choose all that apply): Grumpy extends Exception {} Dopey extends Grumpy {} Happy extends IOException {} Sleepy extends IllegalStateException {} Sneezy extends Throwable {} A. Four of the classes are CHECKED exceptions. B. Two of the classes are UNchecked exceptions. C. None of the class declarations contain any compilation errors.

B, D. The try-with-resources statement requires resources that implement AutoCloseable. While Closeable extends AutoCloseable, it is certainly possible to have a class that implements AutoCloseable and works with try-with-resources but does not implement Closeable, making Option A incorrect. Option B is correct and a valid statement about how resources are closed in try-with-resources statements. Option C is incorrect because the exception in the try block is reported to the caller, while the exception in the close() method is suppressed. Option D is the other correct answer because neither catch nor finally are required when try-with-resources is used. Lastly, Option E is incorrect. While the AutoCloseable does define a close() method that throws a checked exception, classes that implement this method are free to drop the checked exception, per the rules of overriding methods

Which statements about try-with-resources are true? (Choose two.) A. Any resource used must implement Closeable. B. If more than one resource is used, then the order in which they are closed is the reverse of the order in which they were created. C. If the try block and close() method both throw an exception, the one thrown by the try block is suppressed. D. Neither a catch nor a finally block is required. E. The close() method of the resources must throw a checked exception.

C. Options (a) and (d) are incorrect. -enable and -enableAssertions are invalid switch options. The correct switch options to enable assertions are -ea and -enableassertions. If you use an invalid argument (like -enable) the program will not run, but will exit immediately with an "Unrecognized option" error. Option (b) is incorrect. With assertions enabled, assert(calc()) will evaluate to assert(false) and throw an AssertionError, exiting the application, before printing any values. Option (c) is correct. With assertions disabled, the assert(calc()) statement is equivalent to an empty statement or a nonexistent line of code. So method calc() isn't executed, and the value of the static variable foo(10) is printed.

class AssertTest { static int foo = 10; static boolean calc() { ++foo; return false; } public static void main(String args[]) { assert ( calc() ); System.out.println(foo); } } // Select the correct options: A. If executed with >java -enable AssertTest, it print 11; B. If executed with >java -ea AssertTest, it will print 10; C. If executed with >java -da AssertTest, it will print 10; D. If executed with >java -enableAssertions AssertTest, it throw an AssertionError and print 11; E. None of the above

B, E, F To override read() in the Base interface, read() in the Derived interface must eitherdeclare to throw a BaseException, any derived classes of BaseException, any runtimeexception or errors, or no exception. Option (a) is incorrect because FileNotFoundException is unrelated to BaseException. Options (C), (D), and (G) are incorrect because IOException, Exception, and Throwable are all superclasses of BaseException (and not subclasses) and thereforeinvalid when overriding method read().

class BaseException extends IOException {} class DerivedException extends FileNotFoundException {} interface Base { void read() throws BaseException; } interface Derived extends Base { *void read()* } // Which definition of read() compiles successfully? (choose all options) A. void read() throws FileNotFoundException; B. void read(); C. void read() throws IOException; D. void read() throws Exception; E. void read() throws BaseException; F. void read() throws RuntimeException; G. void read() throws Throwable;

B. The constructor of class Box throws a RuntimeException, and so the box variable isn't initialized in the try-with-resources statement. Method close() of class Box isn't called implicitly because execution didn't proceed inside the try block. When try-with-resources throws an exception, the control is transferred to the catch block. In this case, the exception handler prints "catch: java.lang.Runtime-Exception". The finally block always executes.

class Box implements AutoCloseable { Box() { throw new RuntimeException(); } public void close() throws Exception { System.out.print("close"); throw new Exception(); } } public class EJavaFactory { public static void main(String[] args) { try ( Box b = new Box() ) { b.close(); } catch (Exception e) { System.out.print("Catch: " + e); } finally { System.out.print("Finally"); } } } // What output? A. catch:java.lang.RuntimeException close finally B. catch:java.lang.RuntimeException finally C. catch:java.lang.RuntimeException close D. close finally E. Compilation exception

A, B, C, E Option (a) is correct. It defines the correct syntax to use try with multi-catch, and rethrows the caught instance of BreathingException or DivingException. Option (b) is correct. Though the type of the exception caught in the exceptionhandler is Exception, the superclass of the exceptions thrown by main(), the com-piler knows that the try block can throw only two checked exceptions, BreathingException or DivingException. So this thrown exception is caught and rethrown with more inclusive type checking. Option (c) is correct. The multi-catch statement is correct syntactically. Also, thethrow statement throws a checked DivingException, which is declared by methodmain()'s throws clause. Option (d) is incorrect. The catch block throws an instance of checked exceptionException, the superclass of the exceptions declared to be thrown by main(), whichisn't acceptable. Option (e) is correct. It isn't obligatory to include the names of the runtime excep-tions thrown by a method in its throws clause

class BreathingException extends Exception {} class DivingException extends Exception {} class Swimmer { public void swim() throws BreathingException {} public void dive() throws DivingException {} public static void main(String args[]) throws BreathingException, DivingException { try { Swimmer paul = new Swimmer(); paul.swim(); paul.dive(); } *L1* // Which can be inserted so compiles successfully? (Choose all) } } A. catch(DivingException | BreathingException e) { throw e; } B. catch(Exception e) { throw e; } C. catch(DivingException | BreathingException e) { throw new DivingException(); } D. catch(Exception e) { throw new Exception(); } E. catch(Exception e) { throw new RuntimeException(); }

D. The code does not compile because the throw keyword is incorrectly used in the toss() method declaration. The keyword throws should have been used instead. For this reason, Option D is the correct answer. Since LostBallException inherits Throwable and the main() method handles Throwable, LostBallException is handled by the main() method, making Option B incorrect. Option C is also incorrect because ArrayStoreException is an unchecked exception that extends RuntimeException and is not required to be handled or declared. Finally, if throws was used instead of throw, the entire application would compile without issue and print Caught!, making Option A correct.

class LostBallException extends Exception {} public class Ball { public void toss() *throw* LostBallException { throw new ArrayStoreException(); } public static void main(String[] bouncy) { try { new Ball().toss(); } catch (Throwable e) { System.out.print("Caught!"); } } } // What is the output of the following application? A. Caught! B. The code does not compile because LostBallException is not handled or declared in the main() method. C. The code does not compile because ArrayStoreException is not handled or declared in the toss() method. D. The code does not compile for a different reason.

D. The MissedCallException is a checked exception since it extends Exception and does not inherit RuntimeException. For this reason, the first catch block fails to compile, since the compiler detects that it is not possible to throw this checked exception inside the try block, making Option D the correct answer. Note that if MissedCallException was changed to extend the checked RuntimeException, then the code would compile and the RuntimeException from the finally block would replace the ArrayIndexOutOfBoundsException from the try block in the message reported to the caller, making Option C the correct answer

class MissedCallException extends Exception {} public class Phone { static void makeCall() throws RuntimeException { throw new ArrayIndexOutOfBoundsException("Call"); } public static void main(String[] messages) { try { makeCall(); } catch (MissedCallException e) { throw new RuntimeException("Voicemail"); } finally { throw new RuntimeException("Text"); } } } // Which statement about the following program is true? A. An exception is printed at runtime with Call in the message. B. An exception is printed at runtime with Voicemail in the message. C. An exception is printed at runtime with Text in the message. D. The code does not compile.

D. The play() method declares two checked exceptions, OutOfTuneException and FileNotFoundException, which are handled in the main() method's catch block using the Exception type. The catch block then rethrows the Exception. The compiler is smart enough to know that only two possible checked exceptions can be thrown here, but they both must be handled or declared. Since the main() method only declares one of the two checked exceptions, FileNotFoundException is not handled, and the code does not compile. For this reason, Option D is the correct answer. Note that the main() could have also handled or declared Exception, since both checked exceptions inherit it. If the main() method had declared Exception, then Song finished! would have been printed followed by a stack trace, making Option C the correct answer.

class OutOfTuneException extends Exception { OutOfTuneException(String message) { super(message); } } public class Piano { public void play() throws OutOfTuneException, FileNotFoundException { System.out.pringln("Song finished"); throw new OutOfTuneException("Sour note!"); } public static void main(String... keys) throws OutOfTuneException { final Piano piano = new Piano(); try { piano.play(); } catch (Exception e) { throw e; } finally {} } }// What is the output? A. Song finished! B. An exception is printed with Sour note! in the stack trace. C. Both of the above D. None of the above

A. The try-catch block already catches Exception, so the correct answer would be the one that is not a subclass of Exception. Because IllegalStateException and RingException both inherit from Exception, Options B and C, respectively, are incorrect. In this case, Error extends Throwable and is the only choice that allows the code to compile.

class Player implements AutoCloseable { @Override public void close() throws RingException {} } class RingException extends Exception { public RingException(String message) {} } public static void main(String[] notes) throws Throwable { try (Player p = null) { throw new Exception(); } catch (Exception e) { } catch (_______________) { } } // Which option allow code to compile: A. Error r B. IllegalStateException b C. RingException p D. The code does not compile regardless of the expression used.

A Since a multi-catch is used, the variable in the catch block is effectively final and cannot be reassigned.

public class AhChoo { static class SneezeException extends Exception { } static class SniffleException extends SneezeException { } public static void main(String[] args) throws SneezeException { try { throw new SneezeException(); } catch (SneezeException | RuntimeException e) { *_________________* throw e; } } } // What can be substitute for compiling and run? A. // leave line blank B. e = new Exception(); C. e = new RuntimeException(); D. e = new SneezeException(); E. e = new SniffleException();

E. catch (IOException e | SQLException e) doesn'tcompile. While multiple exception types can be specified in the multi-catch, only one variable name is allowed. The correct syntax is catch(IOException | SQLException e). Other than this, the code is valid. Note that it is legal for blowUp() to have IOException in its signatureeven though that Exception can't be thrown.

public class AllGoesWrong { public static void main(String[] args) { AllGoesWrong a = new AllGoesWrong(); try { a.blowUp(); } catch (IOException *e* | SQLException e) { System.out.println("c"); } finally { System.out.println("d"); } } void blowUp() throws IOException, SQLException { throw new SQLException(); } } // What is the result? A. ad B. acd C. cd D. d E. Compilation fails F. An exception is thrown at runtime

Close 2 Close 1 ex finally

public class Auto implements AutoCloseable { int num; Auto(int num) { this.num = num; } public void close() { System.out.println("Close: " + num); } public static void main(String[] args) { try (Auto a1 = new Auto(1); Auto a2 = new Auto(2)) { throw new RuntimeException(); } catch (Exception e) { System.out.println("ex"); } finally { System.out.println("finally"); } } } What this code prints?

TWDEF

public class AutocloseableFlow { static class Door implements AutoCloseable { public void close() {System.out.print("D"); } } static class Window implements Closeable { public void close() { System.out.print("W"); throw new RuntimeException(); } } public static void main(String[] args) { try (Door d = new Door(); Window w = new Window()) { System.out.print("T"); } catch (Exception e) {System.out.print("E"); } finally { System.out.print("F"); } }

C, D, Since order doesn't matter, both D and C show correct use of the multi-catch block. C catches the IOException from fileBlowUp() directly. Note that databaseBlowUp()is never called at runtime.

public class BadIO { void databaseBlowUp() throws SQLException { throw new SQLException(); } void fileBlowUp() throws IOException { throw new IOException(); } public static void main(String[] args) { try { BadIO a = new BadIO(); a.fileBlowUp(); a.databaseBlowUp(); } //*L1* System.out.println("b"); } catch (Exception e) { System.out.println("c"); } } } // Which, inserted independently at *L1*, produce the output b? (Choose all that apply.) A. catch(Exception e) { B. catch(FileNotFoundException e) { C. catch(IOException e) { D. catch(IOException | SQLException e) { E. catch(IOException e | SQLException e) { F. catch(SQLException e) {

E. When an assert statement has two expressions, thesecond expression must return a value. The only two-expression assertstatement that doesn't return a value is on line 9

public class Clumsy { private static void doStaff() { } public static void main(String[] args) { int j = 7; assert (++j>7); assert (++j>8): "hi"; assert (j>10): j=12; assert (j==12): doStaff(); assert (j==12): new Clumsy(); } } // Which are true? (Choose all that apply.) A. Compilation succeeds B. Compilation fails on line assert (++j>7); C. Compilation fails on line assert (++j>8): "hi"; D. Compilation fails on line assert (j>10): j=12; E. Compilation fails on line assert (j==12): doStaff(); F. Compilation fails on line assert (j==12): new Clumsy();

C. The Closeable interface defines a close() method that throws IOException. The overridden implementation of MyDatabase, which implements Closeable, declares a SQLException. This is a new checked exception not found in the inherited method signature. Therefore, the method override is invalid and the close() method in MyDatabase does not compile, making Option C the correct answer.

public class DatabaseHelper { static class MyDatabase implements Closeable { public void close() throws SQLException { System.out.print("2"); } public void write(String data) {} public String read() {return null;} } public static void main(String... files) throws Exception { try (MyDatabase myDb = new MyDatabase()) { // TODO: Decide what to read/rite } finally { System.out.print("1"); } } } // What is the output of the application? A. 12 B. 21 C. The code does not compile because of the MyDatabase class. D. The code does not compile because of the try-with-resources statement.

RuntimeException Previous exceptions will be lost. (Even in close method of the JammedTurkeyCage.class)

public class JammedTurkeyCage implements AutoCloseable { public void close() throws IllegalStateException { throw new IllegalStateException("Cage door does not close"); } } try ( JammedTurkeyCage t = new JammedTurkeyCage() ) { throw new NullPointerException("turkeys ran off"); } finally { throw new RuntimeException("and we couldn't find them"); }

Exception in thread "main" java.lang.RuntimeException: turkeys ran off at JammedTurkeyCage.main(JammedTurkeyCage.java) Suppressed: java.lang.IllegalStateException: Cage door does not close

public class JammedTurkeyCage implements AutoCloseable { public void close() throws IllegalStateException { throw new IllegalStateException("Cage door does not close"); } } ... try (JammedTurkeyCage t = new JammedTurkeyCage()) { throw new RuntimeException("turkeys ran off"); } catch (IllegalStateException e) { System.out.println("caught: " + e.getMessage()); } what will be printed?

C. The class does not compile because in line r2, brackets {} are used instead of parentheses () in the try-with-resources statement, making Option C the correct answer. If this line was fixed to use parentheses (), then the rest of the class would compile without issue and print This just in! at runtime, making Option A the correct answer.

public class PrintCompany { class Printer implements Closeable { // r1 public void print() { System.out.println("This just in!"); } public void close() { } } public void printHeadlines() { try *{* Printer p = new Printer() *}* { // r2 p.print(); } } public static void main(String[] headlines) { new PrintCompany().printHeadlines(); // r3 } } A. This just in! B. The code does not compile because of line r1 . C. The code does not compile because of line r2 . D. The code does not compile because of line r3 .

Not compile. Method close() throws checked exception and need to be declared or handled.

public class StuckTurkeyCage implements AutoCloseable { public void close() throws Exception { throw new Exception("Cage door does not close"); } public static void main(String[] args) { try ( StuckTurkeyCage t = new StuckTurkeyCage() ) { System.out.println("put turkeys in"); } } } // What output?

D. The catch variable d is of type BearException that cannot be assigned an instance ofthe superclass RuntimeException without an explicit cast. For this reason, the first catch block does not compile in tellStory(). The second catch block also does not compile, albeit for a slightly different reason. A catch variable in a multi-catch block must be effectively final because the precise type is not known until runtime. Therefore, the compiler does not allow the variable e to be reassigned. For these two reasons, Option D is the correct answer. Note that the first catch block does allow the catch variable d to be reassigned, it just must be to a class that inherits BearException or is an instance of BearException.

public class Tale { class BearException extends RuntimeException {} class WolfException extends RuntimeException {} class DragonException extends RuntimeException {} public int tellStory() { try {} catch (BearException d) { d = new RuntimeException(); throw d; } catch (WolfException | DragonException e) { e = new RuntimeException(); throw e; } return 3; } public static void main(String... wand) throws RuntimeException { new Tale().tellStory(); } } // Which statement about the following program is correct? A. The class compiles and does not print anything at runtime. B. The code does not compile solely due to the first catch block in tellStory() . C. The code does not compile solely due to the second catch block in tellStory() D. The code does not compile due to errors in both catch blocks in tellStory() .


Ensembles d'études connexes

group decision making and problem solving chapter 11

View Set

INCREASES and DECREASES panel 3: Kidney Function Panel (SST Tube)

View Set

CAP 100 Unit 3 Exam Essentials 2018

View Set

Chapter 54: Caring for Clients with Breast Disorders

View Set