Try-Catch
Overview
Exceptions are abnormal events that disrupt the normal flow of a program (like trying to open a file that doesn't exist, or losing network connection during a database query). If you don't 'catch' an exception, the JVM forcefully crashes your program. Try-Catch blocks are your safety net. You 'try' to execute risky code, and if it blows up, you 'catch' the explosion and handle it gracefully, allowing the rest of your application to keep running.
Syntax
The `try` block is mandatory. You must follow it with either a `catch` block, a `finally` block, or both. `finally` is typically used to close files or database connections so memory doesn't leak.
public void divideNumbers() {
int x = 10;
int y = 0;
try {
// The risky code goes here
int result = x / y;
System.out.println("Result: " + result); // This line is skipped!
} catch (ArithmeticException e) {
// This block runs ONLY if ArithmeticException occurs
System.out.println("Error: Cannot divide by zero!");
} finally {
// This block ALWAYS runs, whether an error happened or not
System.out.println("Cleaning up resources...");
}
}Try-With-Resources is a game changer. Any object that implements `AutoCloseable` (like Scanners, Streams, or DB connections) placed in the `try(...)` parenthesis will be automatically closed, preventing massive memory leaks.
// Multi-Catch (Java 7+)
try {
processFile();
} catch (IOException | SQLException e) {
System.out.println("A serious error occurred: " + e.getMessage());
}
// Try-With-Resources (Automatically closes the scanner!)
try (Scanner scanner = new Scanner(new File("data.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}Common Pitfalls
- Swallowing Exceptions: Catching an exception but leaving the catch block completely empty. This makes debugging a nightmare because the error vanishes silently.
- Catching `Exception` (the parent class) first. Catch blocks must be ordered from most specific to least specific. Catching `Exception` at the top will trap everything, making subsequent catch blocks unreachable code.
Interview Tips
- In interviews, emphasize that catching generic 'Exception' is an anti-pattern. You should always catch specific exceptions first.
Real-World Example
In web servers (like Tomcat or Spring), an unhandled exception would crash the whole server. Try-catch ensures only the single web request fails, returning a 500 status code, while the server keeps handling other users.
public class ApiController {
public HttpResponse fetchUserData(int userId) {
try {
User user = database.getUser(userId);
return new HttpResponse(200, user.toJson());
} catch (DatabaseConnectionException e) {
log.error("DB failed for user " + userId, e);
return new HttpResponse(503, "Service Unavailable");
} catch (Exception e) {
log.error("Unknown error", e);
return new HttpResponse(500, "Internal Server Error");
}
}
}