Learning Java
Custom Search

Previous Next

The Finally Block

The finally block is used when you want to execute some code no matter what happens in the try or catch blocks. The finally block requires you to have a try block, but does not require the catch block.

The following example contains all 3 blocks, try...catch...finally...

import java.io.*;

public class TryCatchFinally {

    public static void main(String[] arguments) {
        int quotient = 0;
        int dividend = 20;
        int[] divisor  = { 6, 4, 3, 2, 0, -5};

	for (int i = 0; i < 7; i++) {
    	   try {
	      quotient = dividend / divisor[i];
	      System.out.println("quotient = " + quotient);

    	   } catch(ArithmeticException e) {
	      System.out.println("Divisor is " + divisor[i] 
                  + ".   Exception : "+ e.getMessage());

    	   } catch(ArrayIndexOutOfBoundsException e) {
	      System.out.println("Index is " + i 
                  + ".   Exception : "+ e.getMessage());

    	   } catch(Exception e) {
	      System.out.println("Calc #" + i 
                  + ": Exception : " + e.getMessage());

    	   } finally {
	      System.out.println("Double the quotient and get " 
                  + (2 * quotient));
	   }
	}
    }
}

The following example only contains the try...catch... blocks.

import java.io.*;

public class TryFinally {

    public static void main(String[] arguments) {
        int total = 0;
        int[] numbers  = { 6, 4, 3, 2, -2, -5};
        int i = 0;

    	try {
	   for (i = 0; i < 6; i++) {
	      total = total + numbers[i];
	      System.out.println(i + " subtotal = " + total);

    	      if (numbers[i] < 0) return;
           }
    	} finally {
	   System.out.println("Stopped at " + i);
	}
        return;
    }
}

 

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved