Java Reference
In-Depth Information
Typically, you use a finally block to write cleanup code. For example, you may obtain some resources in your
program that must be released when you are done with them. A try-finally block lets you implement this logic. Your
code structure would look as follows:
try {
// Obtain and use some resources here
}
finally {
// Release the resources that were obtained in the try block
}
You write try-finally blocks frequently when you write programs that perform database transactions and file
input/output. You obtain and use a database connection in the try block and release the connection in the finally
block. When you work with a database-related program, you must release the database connection, which you
obtained in the beginning, no matter what happens to the transaction. It is similar to executing statements in set-1
and set-2 as described above. Listing 9-11 demonstrates the use of a finally block in four different situations.
Listing 9-11. Using a finally Block
// FinallyTest.java
package com.jdojo.exception;
public class FinallyTest {
public static void main(String[] args) {
int x = 10, y = 0, z;
try {
System.out.println("Before dividing x by y.");
z = x / y;
System.out.println("After dividing x by y.");
}
catch (ArithmeticException e) {
System.out.println("Inside catch block - 1.");
}
finally {
System.out.println("Inside finally block - 1.");
}
System.out.println("-------------------------------");
try {
System.out.println("Before setting z to 2449.");
z = 2449;
System.out.println("After setting z to 2449.");
}
catch (Exception e) {
System.out.println("Inside catch block - 2.");
}
finally {
System.out.println("Inside finally block - 2.");
}
 
Search WWH ::




Custom Search