天天看點

finally_Keyword

Java finally Block

Java Exceptions Tutorial

In the previous article, we have learned how to use Java try/catch Block to handle exceptions in Java. In this article, we will how and why to use finally block with examples.

finally, Block Overview

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether an exception is handled or not.
  • Java finally block follows try/catch block.

    For each try block, there can be zero or more catch blocks, but only one finally block.

    The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

    finally Block Different Scenario Examples

    Here is an example program that shows three methods that exit in various ways, none without executing their finally clauses:

Below example covers the below scenarios:

Throw an exception out of the method

Return from within a try block

Execute a try block normally

// Demonstrate finally.
class FinallyDemo {
 // Throw an exception out of the method.
 static void procA() {
    try {
     System.out.println("inside procA");
     throw new RuntimeException("demo");
    } finally {
       System.out.println("procA's finally");
    }
 }

 // Return from within a try block.
 static void procB() {
   try {
     System.out.println("inside procB");
     return;
   } finally {
     System.out.println("procB's finally");
   }
 }

 // Execute a try block normally.
 static void procC() {
   try {
     System.out.println("inside procC");
   } finally {
     System.out.println("procC's finally");
   } 
 }

 public static void main(String args[]) {
   try {
     procA();
   } catch (Exception e) {
     System.out.println("Exception caught");
   }
    procB();
    procC();
  }
}      

Output:

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally      

finally, Block Examples

public class FileInputStreamExample {
    public static void main(String[] args) {

        FileInputStream fis = null;
        try {
            File file = new File("sample.txt");
            fis = new FileInputStream(file);
            int content; 
            while ((content = fis.read()) != -1) {
               // convert to char and display it
               System.out.print((char) content);
            }
       } catch (IOException e) {
            e.printStackTrace();
       } finally {
           if(fis != null){
               try {
                   fis.close();
               } catch (IOException e) {
                  // TODO Auto-generated catch block
                    e.printStackTrace();
               }
           }
        }
    }
}      

Example 2: When we use JDBC connection to communicate with a database. The resource that we have used are ResultSet, Statement, and Connection (in that order) should be closed in a finally block when you are done with them, something like that:

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* ignored */}
    }
}