Try-with-Resource:- Hello Friends, before Java 7, we need to use Catch or finally block with the Try Block in Java. But In Java 7, we use Try block with resource, through which we can use the Try Block without catch or finally block. This means that it's not mandatory to use the catch or finally block with the try block.
Simply try-with-resource ensure that resource is closed properly. Any Class that implements the Closeable interface that can be used as a resource with the try block.
Example:-
package com.exception;
import java.io.Closeable;
import java.io.IOException;
public class MyClass implements Closeable {
@Override
public void close() throws IOException {
System.out.println("Inside the Close Method");
}
}
package com.exception;
import java.io.IOException;
public class MyException {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try(MyClass myClass=new MyClass()){
}
}
}
In the above program we use the MyClass class and implements that class with the Closeable interface. We used the MyClass class with in the try block and you can see that we are have not used any catch or finally block with it.
0 Comment(s)