Nearby lessons

61 of 125

Java - try-with-resources

📌 What You Will Learn
  • What an exception is and why programs crash
  • The try, catch, finally structure
  • Checked vs unchecked exceptions (with the updated rule)
  • throw vs throws
  • Creating your own (custom) exceptions
  • try-with-resources — the modern way

try-with-resources is a core concept of the Java language. This lesson explains try-with-resources — The Modern Clean Way with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

try-with-resources — The Modern Clean Way

Updated knowledge (Java 7+): when you open a file, stream or database connection, it must be closed after use. The old way was a messy finally block. try-with-resources closes everything automatically:

The resource class must implement the AutoCloseable interface (BufferedReader, FileInputStream, Connection all do). This removes the risk of forgetting to close.

In simple words: try-with-resources closes the resource for you automatically. Declare it inside the parentheses and Java calls close() when the try block ends — even if an exception is thrown.
Example01
JCode Cell
1import java.io.*;
2 
3class TryWithResources {
4 public static void main(String[] args) {
5 // resource is auto-closed after try ends
6 try (BufferedReader br = new BufferedReader(new FileReader("abc.txt"))) {
7 System.out.println(br.readLine());
8 } catch (IOException e) {
9 System.out.println("File problem: " + e.getMessage());
10 }
11 }
12}
📝 Key Takeaways
  • Exception = a run-time problem that stops the program; handling prevents the crash.
  • try keeps risky code, catch handles the problem, finally always runs.
  • Checked exceptions must be handled; unchecked (RuntimeException) are optional to handle.
  • throw throws an exception; throws warns that a method may throw one.
  • Custom exceptions extend Exception or RuntimeException for business rules.
  • try-with-resources (Java 7+) closes files/connections automatically.
  • Errors (like OutOfMemoryError) are system problems — not meant to be caught.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1