Questions
What is the difference between a `checked` and an `unchecked` exception in Java?
The Scenario
You are a backend engineer at a fintech company. You are writing a new service that needs to interact with a third-party API. The API can throw a variety of different exceptions, and you need to decide how to handle them.
The Challenge
Explain the difference between a checked and an unchecked exception in Java. What are the pros and cons of each approach, and how would you decide which one to use for a given exception?
A junior engineer might not be aware of the difference between a `checked` and an `unchecked` exception. They might just catch all exceptions and log them, which would not be a very robust solution.
A senior engineer would be able to provide a detailed explanation of the differences between a `checked` and an `unchecked` exception. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Key Differences
| Feature | checked Exception | unchecked Exception |
|---|---|---|
| Compiler | The compiler checks that the exception is handled. | The compiler does not check that the exception is handled. |
throws | A method that can throw a checked exception must declare it in its throws clause. | A method that can throw an unchecked exception does not need to declare it in its throws clause. |
| Subclasses | Subclasses of Exception (but not RuntimeException). | Subclasses of RuntimeException. |
| Use Cases | For recoverable errors that the caller should be able to handle. | For programming errors that should not be caught. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use a checked exception for any exceptions that can be thrown by the third-party API. This will force the caller to handle the exception, which will make our code more robust.
We should use an unchecked exception for any programming errors in our own code, such as a NullPointerException.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
checked Exception:
public void myMethod() throws MyCheckedException {
// ...
throw new MyCheckedException("Something went wrong.");
}unchecked Exception:
public void myMethod() {
// ...
throw new MyUncheckedException("Something went wrong.");
} Practice Question
You are writing a library and you want to make sure that the caller handles a particular error. Which of the following would you use?