Quiz: Clean Error Handling and Unit Tests in Java

Total: 5 questions

1. 

Why are exceptions better than error codes?

An error code such as -1 or false mixes the normal result with the failure and must be checked by every caller immediately; if a check is forgotten, the program continues in a wrong state and fails far away. An exception separates the two paths: the main flow reads straight through, and the failure cannot be lost silently.

2. 

What should the message of an exception contain?

Enough context to understand the failure from the log alone: which operation failed, with which input and why, for example "Cannot ship order 42: status is NEW, expected PAID". When you wrap a lower-level exception, pass it as the cause so the stack trace keeps the whole chain.

3. 

What should a method return instead of null?

For a collection, an empty collection such as List.of(): callers can iterate, stream and count it without any null check. For a single value that may be missing, Optional. For a missing configuration or a broken invariant, throw an exception with a clear message.

4. 

What is the given-when-then structure of a unit test?

A test has three parts: given prepares the data, when performs the operation under test, and then checks the result. The same structure is known as Arrange-Act-Assert. Separating the parts with comments or blank lines lets the reader find the key line of the test at once.

5. 

What does F.I.R.S.T. mean for unit tests?

Five properties of good unit tests: Fast (the suite runs in seconds), Independent (tests pass in any order), Repeatable (the same result on any machine, at any time), Self-validating (the test passes or fails by itself) and Timely (tests are written together with the code).

Page 1 of 1