Guaranteeing a Block of Code Is Executed by Placing the code into the finally clause. - Java Language Basics

Java examples for Language Basics:try catch finally

Description

Guaranteeing a Block of Code Is Executed by Placing the code into the finally clause.

Demo Code

import java.io.FileOutputStream;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
  static Lock myLock = new ReentrantLock();
  static Random random = new Random();
  
  public static void main(String[] args) {
    myLock.lock();/*  w ww .  j  a  v  a  2 s  .com*/
    try {
      int number = random.nextInt(5);
      int result = 100 / number;
      System.out.println("A result is " + result);
      try (FileOutputStream file = new FileOutputStream("file.out")) {
        file.write(result);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      myLock.unlock();
    }
  }
}

Result


Related Tutorials