Exception handling should explain try, catch, finally, throw, throws, checked exceptions, unchecked exceptions, and the difference between handling and hiding a failure.
Use Java exceptions to separate successful results from failures, catch only where recovery or context is possible, and preserve the original cause when rethrowing.
Use try for risky code, catch for handling specific exceptions, and finally for cleanup that should run whether an exception occurs or not.
public class TryCatchDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException ex) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Done");
}
}
}
Checked exceptions must be handled or declared. Unchecked exceptions extend RuntimeException and usually indicate programming mistakes or invalid inputs.
| Type | Examples | Compiler Requires Handling? |
|---|---|---|
| Checked | IOException, SQLException | Yes |
| Unchecked | NullPointerException, IllegalArgumentException | No |
| Error | OutOfMemoryError, StackOverflowError | No; usually do not catch |
throw creates and sends an exception. throws declares that a method may pass an exception to its caller.
class AgeValidator {
static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}
Use try-with-resources for objects that must be closed, such as files, streams, and database resources.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileReadDemo {
public static void main(String[] args) throws IOException {
String content = Files.readString(Path.of("notes.txt"));
System.out.println(content);
}
}
A catch block should either recover, translate the error into a clearer domain response, or log and rethrow. Empty catch blocks are dangerous because they hide failures and make debugging harder.
Exception handling lets Java code respond to failures in a controlled way. try contains risky code, catch handles a specific exception, and finally runs cleanup logic whether the operation succeeds or fails. The aim is not to silence errors; the aim is to protect the program and give a useful recovery path.
Good exception handling starts by catching the right exception at the right level. A NumberFormatException near input parsing can show a helpful validation message. A database exception might need logging and a retry or user-friendly failure response. Catching Exception everywhere makes debugging harder because it hides what actually went wrong.
String input = "twenty";
try {
int age = Integer.parseInt(input);
System.out.println(age);
} catch (NumberFormatException ex) {
System.out.println("Please enter age using digits only.");
}
No. Use them for exceptional failures, not expected choices.
It avoids hiding unrelated bugs and lets the handler respond appropriately.
Cleanup that must run whether the operation succeeds or fails.
Explore 500+ free tutorials across 20+ languages and frameworks.