finally
block which is used to execute cleanup code and release resources like files, database connections, or network streams.
try
block, eliminating the need for a finally
block for cleanup.
AutoCloseable
or Closeable
interface (like FileInputStream
, BufferedReader
, Scanner
, Connection
etc.).
try
block.
try (ResourceType resource = new ResourceType())
{
// use the resource
}
catch (ExceptionClassType e)
{
// handle exception
}
;
separation
try ( ResourceType1 res1 = new ResourceType1();
ResourceType2 res2 = new ResourceType2() )
{
// use resources
}
catch (ExceptionClassType e)
{
// handle exception
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesDemo
{
public static void main(String[] args)
{
System.out.println("----- App Started -----");
// try-with-resources automatically closes BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("test.txt")))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
System.out.println("IOException occurred: " + e);
}
System.out.println("----- App Finished Successfully -----");
}
}
----- App Started ----- Line 1 from test.txt Line 2 from test.txt ... ----- App Finished Successfully -----
finally
block to close the resource.
AutoCloseable
or Closeable
.
Throwable.getSuppressed()
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.