
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Changes Introduced in JDK 7 Related to Exception Handling in Java
Since Java 7 try-with resources was introduced. In this we declare one or more resources in the try block and these will be closed automatically after the use. (at the end of the try block)
The resources we declare in the try block should extend the java.lang.AutoCloseable class.
Example
Following program demonstrates the try-with-resources in Java.
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopying { public static void main(String[] args) { try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt")); FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){ byte[] buffer = new byte[1024]; int length; while ((length = inS.read(buffer)) > 0) { outS.write(buffer, 0, length); } System.out.println("File copied successfully!!"); } catch(IOException ioe) { ioe.printStackTrace(); } } }
Output
File copied successfully!!
Advertisements