← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 8 of 8

Java का try-with-resources

Try-with-resources files जैसी चीज़ें अपने आप बंद करता है जब आप खत्म करें, एक door जैसा जो आपके पीछे खुद बंद हो जाता है। यह manual clean-up replace करता है।
Syntax
java
try (ResourceType resource = new ResourceType()) {
    // use resource; closed automatically
} catch (ExceptionType e) {
    // handle
}

The try-with-resources Syntax

एक try block के parentheses के अंदर try (Resource r = new Resource()) लिखना Java को उस resource के lifecycle को आपके लिए manage करने को कहता है।

Resource तब खुलता है जब try block शुरू होता है और इसके बंद होने की गारंटी है जब यह खत्म हो, चाहे block normally खत्म हो या एक exception throw करे।

उदाहरण: The try-with-resources Syntax

java
import java.io.FileWriter;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException {
		try (FileWriter writer = new FileWriter("data.txt")) { // opened in the parentheses
			writer.write("Hello");
		} // closed automatically here
		System.out.println("Done");
	}
}

AutoCloseable and close()

सिर्फ वे objects जिनकी class AutoCloseable interface (या इसका subtype Closeable) implement करती है एक try-with-resources statement में उपयोग किए जा सकते हैं, क्योंकि Java को अपने आप call करने के लिए एक close() method चाहिए।

आम examples में FileReader, BufferedReader, और JDBC की Connection और Statement classes शामिल हैं।

उदाहरण: AutoCloseable and close()

java
// Define the class Resource
class Resource implements AutoCloseable {
	public void close() {
		// Print a line to the console
		System.out.println("Resource closed");
	}
}
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try (Resource r = new Resource()) {
			// Print a line to the console
			System.out.println("Using resource");
		}
	}
}

Why It Replaces finally Cleanup

इस syntax से पहले, एक resource सुरक्षित रूप से बंद करने का मतलब था इसे try block से पहले खोलना और एक finally block में बंद करना, जो verbose था और गलत होना आसान (एक null check भूल जाना, या गलत order में बंद करना)। try-with-resources उस boilerplate को पूरी तरह हटा देता है और resources को उनके खुलने के उल्टे order में बंद करता है।

उदाहरण: Why It Replaces finally Cleanup

java
import java.io.FileWriter;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException {
		FileWriter writer = new FileWriter("data.txt");
		try {
			writer.write("Hello");
		} finally {
			writer.close(); // old, verbose, error-prone way
		}
	}
}

Multiple Resources

आप एक try-with-resources statement में कई resources खोल सकते हैं उनकी declarations को semicolons से अलग करके, उदाहरण के लिए try (FileReader fr = ...; BufferedReader br = ...)।

Java उन्हें अपने आप उल्टे declaration order में बंद करता है, इसलिए आखिरी खुला resource पहला बंद होने वाला है।

उदाहरण: Multiple Resources

java
class Resource implements AutoCloseable {
	String name;
	Resource(String name) { this.name = name; }
	public void close() {
		System.out.println(name + " closed");
	}
}
public class Main {
	public static void main(String[] args) {
		try (Resource a = new Resource("A"); Resource b = new Resource("B")) {
			System.out.println("Using both");
		} // closed in reverse order: B then A
	}
}

Suppressed Exceptions

अगर try block के अंदर code एक exception throw करता है और फिर resource बंद करना भी throw करता है, Java दूसरा exception नहीं खोता, यह इसे पहले से एक "suppressed" exception के रूप में attach करता है, getSuppressed() के ज़रिए retrievable।

यह पुराने finally-block pattern से ज़्यादा informative है, जहां एक close() failure चुपचाप original error overwrite कर सकती थी।

उदाहरण: Suppressed Exceptions

java
// Define the class Resource
class Resource implements AutoCloseable {
	public void close() {
		// Throw RuntimeException to signal an error
		throw new RuntimeException("Close failed");
	}
}
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try (Resource r = new Resource()) {
			// Throw RuntimeException to signal an error
			throw new RuntimeException("Body failed");
		// Handle RuntimeException if it was thrown
		} catch (RuntimeException e) {
			// Print a line to the console
			System.out.println(e.getMessage());
			for (Throwable suppressed : e.getSuppressed()) {
				System.out.println("Suppressed: " + suppressed.getMessage());
			}
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Parentheses में एक ऐसा variable उपयोग करना जो AutoCloseable नहीं, जो एक compile error है।
  2. यह मान लेना कि resource block के बाद अब भी खुला है, जब यह अपने आप बंद होता है।
  3. Suppressed exceptions नज़रअंदाज़ करना, इसलिए सिर्फ main exception पढ़ते समय एक close error खो जाती है।
चैप्टर सारांश
  • Exceptions runtime पर errors represent करते हैं और try-catch से handle किए जाते हैं, कई catch blocks सहित।
  • finally, throw, और throws cleanup और exceptions कैसे raised या declared होते हैं control करते हैं।
  • Custom exceptions, exception hierarchy, और try-with-resources आपको errors साफ़ तरीके से handle करने में मदद करते हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.