Using a finally Block with try catch - Java Language Basics

Java examples for Language Basics:try catch finally

Introduction

A finally block is executed whether or not any exceptions are thrown by the try block or caught by any catch blocks.

Its purpose is to let you clean up any resources that might be left behind by the exception, such as open files or database connections.

The basic framework for a try statement with a finally block is this:

try
{
      statements that can throw exceptions
}
catch (exception-type identifier)
{
      statements executed when exception is thrown
}
finally
{
      statements that are executed whether or not exceptions occur
}

A Program That Uses A Finally Clause

Demo Code

public class Main
{
    public static void main(String[] args)
    {/*  w  w  w .j  a va 2 s  . co m*/
    try
    {
      int answer = divideTheseNumbers(5, 0);
    }
    catch (Exception e)
    {
      System.out.println("Tried twice, still didn't work!");
    }
  }

  public static int divideTheseNumbers(int a, int b) throws Exception
  {
    int c;
    try
    {
      c = a / b;
      System.out.println("It worked!");
    }
    catch (Exception e)
    {
      System.out.println("It didn't work the first time.");
      c = a / b;
      System.out.println("I worked the second time!");
    }
    finally
    {
      System.out.println("Better clean up my mess.");
    }
    System.out.println("It worked after all.");
    return c;

  }
}

Related Tutorials