مرکزی مواد پر جائیں
eLearner.app
ماڈیول 5 · سبق 2 از 2کورس میں 10/14~12 min
ماڈیول اسباق (2/2)

وسائل کے ساتھ کوشش کریں۔

In older versions of Java, managing resources that require explicit closing (such as files, database connections, or network streams) required a mandatory finally block to ensure they were closed. This led to verbose and leak-prone code.

Java 7 introduced the try-with-resources statement, which guarantees the automatic closure of all resources declared within the try block, provided they implement the AutoCloseable interface.

The Syntax

Resources are declared and initialized inside parentheses immediately after the try keyword.

Code
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
    System.out.println(line);
} catch (IOException e) {
    System.out.println("I/O Error: " + e.getMessage());
}
// br is closed automatically here, even if an exception occurs

Declaring Multiple Resources

You can instantiate multiple resources inside the same try block, separating them with a semicolon ;. The resources will be closed in reverse order of their declaration.

Code
try (
    FileReader fr = new FileReader("input.txt");
    FileWriter fw = new FileWriter("output.txt")
) {
    // Use resources
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}

Creating Custom Resources

A custom resource can be used in a try-with-resources block as long as it implements java.lang.AutoCloseable and overrides the close() method.

Code
public class DatabaseConnection implements AutoCloseable {
    public void query(String sql) {
        System.out.println("Running query: " + sql);
    }

    @Override
    public void close() {
        System.out.println("Connection closed!");
    }
}

Try it yourself

ورزش#java.m5.l2.e1
کوششیں: 0لوڈ ہو رہا ہے…

Complete the readFile method using the try-with-resources statement to initialize a BufferedReader wrapping a FileReader on path. In the catch block, intercept IOException and print 'Error reading file'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Declare the `BufferedReader` in parentheses right after `try`, and implement `IOException` handling.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#java.m5.l2.e2
کوششیں: 0لوڈ ہو رہا ہے…

Instantiate the custom resource CustomResource inside a try-with-resources block, invoke the doWork() method on it, and handle Exception by printing 'Error'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Use `try (CustomResource res = new CustomResource())` and call `res.doWork();` inside it.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#java.m5.l2.e3
کوششیں: 0لوڈ ہو رہا ہے…

Declare both FirstResource and SecondResource in the same try-with-resources construct. Handle Exception by printing 'Error'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Separate the declaration of the two resources inside the parentheses of `try` using a semicolon `;`.

3 کوششوں کے بعد حل دستیاب ہے۔