0% found this document useful (0 votes)
4 views7 pages

Try-with-resources Feature in Java.pptx

The Try-with-resources statement in Java allows for the declaration of resources that must be closed after use, preventing resource leaks. It simplifies resource management by automatically closing any object that implements java.lang.AutoCloseable at the end of the try block. An example demonstrates its use with a FileOutputStream to write to a file without requiring a separate finally block for resource closure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Try-with-resources Feature in Java.pptx

The Try-with-resources statement in Java allows for the declaration of resources that must be closed after use, preventing resource leaks. It simplifies resource management by automatically closing any object that implements java.lang.AutoCloseable at the end of the try block. An example demonstrates its use with a FileOutputStream to write to a file without requiring a separate finally block for resource closure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Try-with-resources Feature

in Java
• In Java, the Try-with-resources statement is a try statement that
declares one or more resources in it.
• A resource is an object that must be closed once your program
is done using it.
• For example, a File resource or a Socket connection resource.
The try-with-resources statement ensures that each resource is
closed at the end of the statement execution.
• If we don’t close the resources, it may constitute a resource leak
and also the program could exhaust the resources available to
it.
• You can pass any object as a resource that implements
java.lang.AutoCloseable, which includes all objects which
implement java.io.Closeable.
• By this, now we don’t need to add an extra finally block for just
passing the closing statements of the resources. The resources
will be closed as soon as the try-catch block is executed.
• Syntax: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
• Example 1: try-with-resources having a single resource
// Java Program for try-with-resources having single resource
import java.io.*;
class examtry {
public static void main(String[] args)
{
try (FileOutputStream fos
= new FileOutputStream("gfgtextfile.txt"))
{ String text = "Hello World. This is my java program";
byte arr[] = text.getBytes();
fos.write(arr);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(
"Resource are closed and message has been written into the
gfgtextfile.txt");
}
}

You might also like