Sub topic 8
Handling Failures: Non-2xx Statuses, IOException, and Interruption
This chapter assumes that you understand Java checked exceptions, HTTP status codes, and the basic use of HttpClient.send. It also assumes Java 11 or later.
An HTTP request can fail in two different ways:
- The server can return an HTTP response with a failure status, such as
404 Not Foundor500 Internal Server Error. - The client may fail before receiving a usable response because of a timeout, network problem, or thread interruption.
HttpClient.send does not throw an exception for a non-2xx status. It returns an HttpResponse, so your code must inspect statusCode().
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
public class HandleHttpFailures {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/missing"))
.GET()
.build();
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 200 && status < 300) {
System.out.println("Success: " + response.body());
} else {
System.err.println(
"Server returned " + status + ": " + response.body());
}
} catch (HttpTimeoutException e) {
System.err.println("The request timed out: " + e.getMessage());
} catch (IOException e) {
System.err.println("Network or I/O failure: " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("The request was interrupted");
}
}
}HttpTimeoutException is a subtype of IOException, so it must be caught first. The IOException branch handles failures such as DNS errors, refused connections, and broken connections.
InterruptedException means that another thread asked the current thread to stop waiting. After catching it, call Thread.currentThread().interrupt() to restore the interruption flag. This lets higher-level code notice the interruption instead of silently losing it.
| Failure | How it appears | Typical response |
|---|---|---|
| 404 or 500 | Returned `HttpResponse` | Inspect the status and body |
| Request timeout | `HttpTimeoutException` | Report, cancel, or retry carefully |
| Network failure | `IOException` | Log and apply a recovery policy |
| Thread cancellation | `InterruptedException` | Restore the interrupt flag and stop work |
The failure paths can be viewed as two branches:
Exercise
Why should HttpTimeoutException be caught before IOException, and what should the interruption handler do?
Show answer
It is a subtype of IOException, so the specific catch must come first. The interruption handler should restore the flag with Thread.currentThread().interrupt() and stop or propagate the cancellation.