Programmer II Chapter 5: Exceptions, Assertions and Localization Flashcards
What does this code do?
41: var writer = Files.newBufferedWriter(path);
42: writer.append(“This write is permitted but a really bad idea!”);
43: try(writer) {
44: writer.append(“Welcome to the zoo!”);
45: }
46: writer.append(“This write will fail!”);
Runtime exception.
This code compiles but throws an exception on line 46 with the message Stream closed. While it was possible to write to the resource before the try‐with‐resources statement, it is not afterward.
What does this print?
var dt = LocalDateTime.of(2020, Month.OCTOBER, 20, 6, 15, 30);
var formatter1 = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss"); System.out.println(dt.format(formatter1));
var formatter2 = DateTimeFormatter.ofPattern("MM_yyyy_-_dd"); System.out.println(dt.format(formatter2));
var formatter3 = DateTimeFormatter.ofPattern("h:mm z"); System.out.println(dt.format(formatter3));
10/20/2020 06:15:30
102020-_20
Exception in thread “main” java.time.DateTimeException: Unable to extract ZoneId from temporal 2020-10-20T06:15:30
The first example prints the date, with the month before the day, followed by the time. The second example prints the date in a weird format with extra characters that are just displayed as part of the output.
The third example throws an exception at runtime because the underlying LocalDateTime does not have a time zone specified. If ZonedDateTime was used instead, then the code would have completed successfully and printed something like 06:15 EDT, depending on the time zone.
Which of the following classes contain at least one compiler error? (Choose all that apply.)
class Danger extends RuntimeException { public Danger(String message) { super(); } public Danger(int value) { super((String) null); } }
class Catastrophe extends Exception { public Catastrophe(Throwable c) throws RuntimeException { super(new Exception()); c.printStackTrace(); } }
class Emergency extends Danger { public Emergency() {} public Emergency(String message) { super(message); } }
A. Danger
B. Catastrophe
C. Emergency
D. All of these classes compile correctly.
E. The answer cannot be determined from the information given.
C.
Exception and RuntimeException, along with many other exceptions in the Java API, define a no-argument constructor, a constructor that takes a String, and a constructor that takes a Throwable. For this reason, Danger compiles without issue. Catastrophe also compiles without issue. Just creating anew checked exception, without throwing it, does not require it to be handled or declared. Finally, Emergency does not compile. The no-argument constructor in Emergency must explicitly call a parent constructor, since Danger does not define a no-argument constructor.
Which of the following are common types to localize? (Choose all that apply.)
A. Dates B. Lambda expressions C. Class names D. Currency E. Numbers F. Variable names
A, D, E.
Localization refers to user-facing elements. Dates, currency, and numbers are commonlyused in different formats for different countries. Class and variable names, along with lambdaexpressions, are internal to the application, so there is no need to translate them for users.
What is the output of the following code?
import java.io.*; public class EntertainmentCenter { static class TV implements AutoCloseable { public void close() { System.out.print("D"); } } static class MediaStreamer implements Closeable { public void close() { System.out.print("W"); } } public static void main(String[] args) { var w = new MediaStreamer(); try { TV d = new TV(); w; } { System.out.print("T"); } catch (Exception e) { System.out.print("E"); } finally { System.out.print("F"); } } }
A. TWF B. TWDF C. TWDEF D. TWF followed by an exception. E. TWDF followed by an exception. F. TWEF followed by an exception. G. The code does not compile.
G.
A try-with-resources statement uses parentheses, (), rather than braces, {}, for the try section.This is likely subtler than a question that you’ll get on the exam, but it is still important to be on alertfor details. If parentheses were used instead of braces, then the code would compile and print TWDF atruntime.
Which statement about the following class is correct?
1: class Problem extends Exception { 2: public Problem() {} 3: } 4: class YesProblem extends Problem {} 5: public class MyDatabase { 6: public static void connectToDatabase() throw Problem { 7: throws new YesProblem(); 8: } 9: public static void main(String[] c) throw Exception { 10: connectToDatabase(); 11: } 12: }
A. The code compiles and prints a stack trace for YesProblem at runtime.
B. The code compiles and prints a stack trace for Problem at runtime.
C. The code does not compile because Problem defines a constructor.
D. The code does not compile because YesProblem does not define a constructor.
E. The code does not compile but would if Problem and YesProblem were switched on lines 6 and7.
F. None of the above
F.
The code does not compile because the throw and throws keywords are incorrectly used on lines 6,7, and 9. If the keywords were fixed, then the rest of the code would compile and print a stack trackwith YesProblem at runtime.
What is the output of the following code?
LocalDate date = LocalDate.parse("2020–04–30", DateTimeFormatter.ISO_LOCAL_DATE_TIME); System.out.println(date.getYear() + " " \+ date.getMonth() + " "+ date.getDayOfMonth());
A. 2020 APRIL 2 B. 2020 APRIL 30 C. 2020 MAY 2 D. The code does not compile. E. A runtime exception is thrown.
E. A LocalDate does not have a time element. Therefore, a Date/Time formatter is not appropriate.The code compiles but throws an exception at runtime. If ISO_LOCAL_DATE was used, then the codewould compile and option B would be the correct answer.
Assume that all of the files mentioned in the answer choices exist and define the same keys. Which one will be used to find the key in line 8?
6: Locale.setDefault(new Locale("en", "US")); 7: var b = ResourceBundle.getBundle("Dolphins"); 8: System.out.println(b.getString("name"));
A. Dolphins.properties B. Dolphins_US.properties C. Dolphins_en.properties D. Whales.properties E. Whales_en_US.properties F. The code does not compile.
C. Java will first look for the most specific matches it can find, starting withDolphins_en_US.properties. Since that is not an answer choice, it drops the country and looks forDolphins_en.properties, making option C correct. Option B is incorrect because a country withouta language is not a valid locale
For what value of pattern will the following print <005.21> <008.49> <1,234.0>?
String pattern = "\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_"; var message = DoubleStream.of(5.21, 8.49, 1234) .mapToObj(v -> new DecimalFormat(pattern).format(v)) .collect(Collectors.joining( " > < "));
System.out.println(" < "+message+" > ");
A. ##.# B. 0,000.0# C. #,###.0 D. #,###,000.0# E. The code does not compile regardless of what is placed in the blank. F. None of the above
D.
When working with a custom number formatter, the 0 symbol displays the digit as 0, even if it’s notpresent, while the # symbol omits the digit from the start or end of the String if it is not present.Based on the requested output, a String that displays at least three digits before the decimal(including a comma) and at least one after the decimal is required. It should display a second digitafter the decimal if one is available. For this reason, option D is the correct answer. In case you arecurious, option A displays at most only one value to the right of the decimal, printing <5.2> <8.5><1234>. Option B is close to the correct answer but always displays four digits to the left of thedecimal, printing <0,005.21> <0,008.49> <1,234.0>. Finally, option C is missing the zeros paddedto the left of the decimal and optional two values to the right of the decimal, printing <5.2> <8.5><1,234.0>.
Which of the following exceptions must be handled or declared in the method in which they are thrown? (Choose all that apply.)
class Apple extends RuntimeException{} class Orange extends Exception{} class Banana extends Error{} class Pear extends Apple{} class Tomato extends Orange{} class Peach extends Banana{}
A. Apple B. Orange C. Banana D. Pear E. Tomato F. Peach
B, E.
An exception that must be handled or declared is a checked exception. A checked exceptioninherits Exception but not RuntimeException. The entire hierarchy counts, so options B and E areboth correct
Which of the following changes when made independently would make this code compile? (Choose all that apply.)
1: import java.io.*; 2: public class StuckTurkeyCage implements AutoCloseable { 3: public void close() throws IOException { 4: throw new FileNotFoundException("Cage not closed"); 5: } 6: public static void main(String[] args) { 7: try (StuckTurkeyCage t = new StuckTurkeyCage()) { 8: System.out.println("put turkeys in"); 9: } 10: } }
A. Remove throws IOException from the declaration on line 3.
B. Add throws Exception to the declaration on line 6.
C. Change line 9 to } catch (Exception e) {}.
D. Change line 9 to } finally {}.
E. The code compiles as is.
F. None of the above
B, C. The code does not compile, so option E is incorrect. Option A is incorrect because removing theexception from the declaration causes a compilation error on line 4, as FileNotFoundException is achecked exception that must be handled or declared. Option B is correct because the unhandledexception within the main() method becomes declared. Option C is also correct because the exceptionbecomes handled. Option D is incorrect because the exception remains unhandled. Finally, option F isincorrect because the changes for option B or C will allow the code to compile.
Which of the following are true statements about exception handling in Java? (Choose all that apply.)
A. A traditional try statement without a catch block requires a finally block.
B. A traditional try statement without a finally block requires a catch block.
C. A traditional try statement with only one statement can omit the {}.
D. A try‐with‐resources statement without a catch block requires a finally block.
E. A try‐with‐resources statement without a finally block requires a catch block.
F. A try‐with‐resources statement with only one statement can omit the {}
A, B.
A try-with-resources statement does not require a catch or finally block. A traditional try statement requires at least one of the two. Neither statement can be written without a body encased in braces, {}.
Which of the following, when inserted independently in the blank, use locale parameters that are properly formatted? (Choose all that apply.)
import java.util.Locale; public class ReadMap implements AutoCloseable { private Locale locale; private boolean closed = false; void check() { assert !closed; } @Override public void close() { check(); System.out.println("Folding map"); locale = null; closed = true; } public void open() { check(); this.locale = \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_; } public void use() { // Implementation omitted } }
A. new Locale("xM"); B. new Locale("MQ", "ks"); C. new Locale("qw"); D. new Locale("wp", "VW"); E. Locale.create("zp"); F. Locale.create("FF"); G. The code does not compile regardless of what is placed in the blank.
C, D.
The code compiles with the appropriate input, so option G is incorrect. A locale consists of arequired lowercase language code and optional uppercase country code. In the Locale() constructor,the language code is provided first. For these reasons, options C and D are correct. Options E and Fare incorrect because a Locale is created using a constructor or Locale.Builder class
Which of the following is true when creating your own exception class?
A. One or more constructors must be coded.
B. Only custom checked exception classes may be created.
C. Only custom unchecked exception classes may be created.
D. Custom Error classes may be created.
E. The toString() method must be coded.
F. None of the above
D.
You can create custom checked, unchecked exceptions, and even errors. The default constructor is used if one is not supplied. There is no requirement to implement any specific methods
Which of the following can be inserted into the blank to allow the code to compile and run withoutthrowing an exception? (Choose all that apply.)
var f = DateTimeFormatter.ofPattern("hh o'clock"); System.out.println(f.format(\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_.now()));
A. ZonedDateTime B. LocalDate C. LocalDateTime D. LocalTime E. The code does not compile regardless of what is placed in the blank. F. None of the above
F.
The code compiles, but the first line produces a runtime exception regardless of what is inserted into the blank. When creating a custom formatter, any non symbol code must be properly escapedusing pairs of single quotes (‘). In this case, it fails because o is not a symbol. Even if you didn’t knowo wasn’t a symbol, the code contains an unmatched single quote. If the properly escaped value of “hh’o’‘clock’” was used, then the correct answers would be ZonedDateTime, LocalDateTime, andLocalTime. Option B would not be correct because LocalDate values do not have an hour part.