Can we use try without catch in Java?
Yes
Java provides special case where we can use the try without catch block knows as try-with-resources
It is mainly used when we are using some important resource like file or database connection and we want that the file or connection must be closed automatically when the reference goes out of the block.
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Any object that implements java.lang.AutoCloseable interface is a resource.
Syntax
try(classname referencename=new constructor(arguments))
{
}
Example
import java.io.FileWriter;
public class TryWithResourcesTest {
public static void main(String[] args) throws Exception {
try(FileWriter f=new FileWriter("mydata"))
{
f.write("Hello Friends");
}
}
}
Java provides special case where we can use the try without catch block knows as try-with-resources
It is mainly used when we are using some important resource like file or database connection and we want that the file or connection must be closed automatically when the reference goes out of the block.
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Any object that implements java.lang.AutoCloseable interface is a resource.
Syntax
try(classname referencename=new constructor(arguments))
{
}
Example
import java.io.FileWriter;
public class TryWithResourcesTest {
public static void main(String[] args) throws Exception {
try(FileWriter f=new FileWriter("mydata"))
{
f.write("Hello Friends");
}
}
}
showing compilation error while running on java 1.8
ReplyDelete