Java examples for Language Basics:try catch finally
Use Automatic Resource Management with a try-with-resources statement.
import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; public class Main { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream("out.log"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeUTF("This is being written"); // If an exception occurs here, resources will be handled correctly dos.close();//from w w w .j a v a2 s . co m } catch (Exception e) { System.out.println("Some bad exception happened "); } } }