Programmer II Chapter 5: Exceptions, Assertions and Localization Flashcards

1
Q

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!”);

A

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.

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

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));
A

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.

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

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.

A

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.

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

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

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.

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

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

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.

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

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

A

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.

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

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

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.

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

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

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

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

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
A

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

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

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
A

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

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

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

A

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.

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

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

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

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

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

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

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

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

A

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

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

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
A

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.

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

Which of the following statements about resource bundles are correct? (Choose all that apply.)

A. All keys must be in the same resource bundle to be used.
B. A resource bundle is loaded by calling the new ResourceBundle() constructor.
C. Resource bundle values are always read using the Properties class.
D. Changing the default locale lasts for only a single run of the program.
E. If a resource bundle for a specific locale is requested, then the resource bundle for the default locale will not be used.
F. It is possible to use a resource bundle for a locale without specifying a default locale.
A

D, F.
Option A is incorrect because Java will look at parent bundles if a key is not found in a specified resource bundle. Option B is incorrect because resource bundles are loaded from static factory methods. In fact, ResourceBundle is an abstract class, so calling that constructor is not even possible. Option C is incorrect, as resource bundle values are read from the ResourceBundle object directly. Option D is correct because the locale is changed only in memory. Option E is incorrect, as the resource bundle for the default locale may be used if there is no resource bundle for the specified locale (or its locale without a country code). Finally, option F is correct. The JVM will set a default locale automatically, making it possible to use a resource bundle for a locale, even if a locale was not explicitly set.

17
Q

What is the output of the following code?

     import java.io.*;
     public class FamilyCar {
        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) {
           var d = new Door();
           try (d; var w = new Window()) {
              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
A

C.
After both resources are declared and created in the try-with-resources statement, T is printed aspart of the body. Then the try-with-resources completes and closes the resources in reverse order fromwhich they were declared. After W is printed, an exception is thrown. However, the remaining resourcestill needs to be closed, so D is printed. Once all the resources are closed, the exception is thrown andswallowed in the catch block, causing E to be printed. Last, the finally block is run, printing F.Therefore, the answer is TWDEF.

18
Q

Suppose that we have the following three properties files and code. Which bundles are used on lines 8and 9, respectively?
Dolphins.properties
name=The Dolphin
age=0

Dolphins_en.properties
name=Dolly
age=4

Dolphins_fr.properties
name=Dolly

 5: var fr = new Locale("fr");
 6: Locale.setDefault(new Locale("en", "US"));
 7: var b = ResourceBundle.getBundle("Dolphins", fr);
 8: b.getString("name");
 9: b.getString("age");

A. Dolphins.properties and Dolphins.properties
B. Dolphins.properties and Dolphins_en.properties
C. Dolphins_en.properties and Dolphins_en.properties
D. Dolphins_fr.properties and Dolphins.properties
E. Dolphins_fr.properties and Dolphins_en.properties
F. The code does not compile.
G. None of the above

A

D.
Java will use Dolphins_fr.properties as the matching resource bundle on line 7 because it is anexact match on the language of the requested locale. Line 8 finds a matching key in this file. Line 9does not find a match in that file; therefore, it has to look higher up in the hierarchy. Once a bundle ischosen, only resources in that hierarchy are allowed. It cannot use the default locale anymore, but itcan use the default resource bundle specified by Dolphins.properties.

19
Q

Fill in the blanks: When formatting text data, the _________________ class supports parametrized String values, while the _________________ class has built‐in support for missing values.

A. TextFormat, Properties
B. MessageFormat, Properties
C. Properties, Formatter
D. StringFormat, Properties
E. Properties, TextFormat
F. Properties, TextHandler
G. None of the above
A
B. 
The MessageFormat class supports parametrized String values that take input values, while theProperties class supports providing a default value if the property is not set. For this reason, option B is correct.
20
Q

Which changes, when made independently, allow the following program to compile? (Choose all thatapply.)

 1: public class AhChoo {
 2: static class SneezeException extends Exception {}
 3: static class SniffleException extends SneezeException {}
 4: public static void main(String[] args) {
 5: try {
 6: throw new SneezeException();
 7: } catch (SneezeException | SniffleException e) {
 8: } finally {}
 9: } }

A. Add throws SneezeException to the declaration on line 4.
B. Add throws Throwable to the declaration on line 4.
C. Change line 7 to } catch (SneezeException e) {.
D. Change line 7 to } catch (SniffleException e) {.
E. Remove line 7.
F. The code compiles correctly as is.
G. None of the above

A
C. 
The code does not compile because the multi-catch on line 7 cannot catch both a superclass and arelated subclass. Options A and B do not address this problem, so they are incorrect. Since the trybody throws SneezeException, it can be caught in a catch block, making option C correct. Option Dallows the catch block to compile but causes a compiler error on line 6. Both of the customexceptions are checked and must be handled or declared in the main() method. A SneezeExceptionis not a SniffleException, so the exception is not handled. Likewise, option E leads to an unhandledexception compiler error on line 6.
21
Q

What is the output of the following code?

     LocalDateTime ldt = LocalDateTime.of(2020, 5, 10, 11, 22, 33);
     var f = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
     System.out.println(ldt.format(f));
A. 3/7/19 11:22 AM
B. 5/10/20 11:22 AM
C. 3/7/19D. 5/10/20
E. 11:22 AM
F. The code does not compile.
G. A runtime exception is thrown.
A

E.

Even though ldt has both a date and time, the formatter outputs only time

22
Q

Fill in the blank: A class that implements _________________ may be in a try‐with‐resources statement. (Choose all that apply.)

A. AutoCloseable
B. Resource
C. Exception
D. AutomaticResource
E. Closeable
F. RuntimeException
G. Serializable
A

A, E. Resources must inherit AutoCloseable to be used in a try-with-resources block. SinceCloseable, which is used for I/O classes, extends AutoCloseable, both may be used.

23
Q

What is the output of the following method if props contains {veggies=brontosaurus,meat=velociraptor}?

 private static void print(Properties props) {
    System.out.println(props.get("veggies", "none")
       \+ " " + props.get("omni", "none"));
 }
A. brontosaurus none
B. brontosaurus null
C. none none
D. none null
E. The code does not compile.
F. A runtime exception is thrown.
A
E. 
The Properties class defines a get() method that does not allow for a default value. It also has agetProperty() method, which returns the default value if the key is not provided
24
Q

What is the output of the following program?

     public class SnowStorm {
        static class WalkToSchool implements AutoCloseable {
           public void close() {
              throw new RuntimeException("flurry");
           }
        }
        public static void main(String[] args) {
           WalkToSchool walk1 = new WalkToSchool();
           try (walk1; WalkToSchool walk2 = new WalkToSchool()) {
              throw new RuntimeException("blizzard");
           } catch(Exception e) {
              System.out.println(e.getMessage()
                 \+ " " + e.getSuppressed().length);
           }
           walk1 = null;
        }
     }
A. blizzard 0
B. blizzard 1
C. blizzard 2
D. flurry 0
E. flurry 1
F. flurry 2
G. None of the above
A

G. The code does compile because the resource walk1 is not final or effectively final and cannot beused in the declaration of a try-with-resources statement. If the line that set walk1 to null wasremoved, then the code would compile and print blizzard 2 at runtime, with the exception inside thetry block being the primary exception since it is thrown first. Then two suppressed exceptions wouldbe added to it when trying to close the AutoCloseable resources

25
Q

What is the output of the following program?

     import java.text.NumberFormat;
     import java.util.Locale;
     import java.util.Locale.Category;
     public class Wallet {
        private double money;
        // Assume getters/setters/constructors provided        private String openWallet() {
           Locale.setDefault(Category.DISPLAY,
              new Locale.Builder().setRegion("us"));
           Locale.setDefault(Category.FORMAT,
              new Locale.Builder().setLanguage("en"));
           return NumberFormat.getCurrencyInstance(Locale.GERMANY)
              .format(money);
        }
        public void printBalance() {
           System.out.println(openWallet());
        }
           public static void main(String... unused) {
           new Wallet(2.4).printBalance();
        }
     }
A. 2,40 €
B. $2.40
C. 2.4
D. The output cannot be determined without knowing the locale of the system where it will be run.
E. The code does not compile.
F. None of the above
A
E. 
The Locale.Builder class requires that the build() method be called to actually create theLocale object. For this reason, the two Locale.setDefault() statements do not compile because theinput is not a Locale, making option E the correct answer. If the proper build() calls were added,then the code would compile and print the value for Germany, 2,40 €. As in the exam, though, youdid not have to know the format of currency values in a particular locale to answer the question. Notethat the default locale category is ignored since an explicit currency locale is selected.