Managing Resources with try/catch Blocks - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

Use Automatic Resource Management with a try-with-resources statement.

Demo Code


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 ");
    }
  }
}

Related Tutorials