1Z0-830 practice question 11 of 25

When can a custom exception be useful?

Full set: 116 questions
Answer options
A:

A. To catch any type of exception using a single catch (Exception e).

B:

B. To signal specific application-related errors beyond standard exceptions.

Correct answer
C:

C. To automatically close resources opened in a try block.

D:

D. To log error messages to a file.

Correct Answer:
B. B. To signal specific application-related errors beyond standard exceptions.
Explanation

Custom exceptions are most useful for signaling specific, application-level error conditions that are not adequately represented by Java's standard built-in exceptions. By creating a custom exception, such as InsufficientFundsException or InvalidTransactionException, a developer can create a more expressive and self-documenting API. This allows calling code to catch and handle specific business-logic failures with greater precision, leading to more robust and maintainable applications.

Why Incorrect

A. Catching a generic Exception is the opposite of the goal of custom exceptions, which is to provide more specific error handling, not less.
C. Automatically closing resources is handled by the try-with-resources statement or a finally block, a feature unrelated to the type of exception being thrown.
D. Logging is a separate concern from signaling an error. While an exception (custom or standard) is typically logged, the exception's purpose is to represent the error state itself.

References

1. Oracle Corporation. (2023). The Java™ Tutorials: Unchecked Exceptions — The Controversy. "If a client can be reasonably expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception." This implies creating custom exception types for recoverable, application-specific scenarios.

2. Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley Professional. Item 71, "Favor the use of standard exceptions," advises using standard exceptions when they fit, but implicitly supports custom exceptions for cases where they do not. Item 72, "Favor checked exceptions for recoverable conditions," further details when to define custom checked exceptions.

Scroll to Top