J2EEOnline
GofPatterns OOPortal
prev next prev next
  Course navigation
 
Lesson 10
Objective
The finally keyword in Java
Code that uses the finally keyword.
   
Determine the results of a block of code that uses the finally keyword.
Before we leave our topic of exceptions, we need to cover one tenacious keyword called finally.
The finally keyword is a strange animal. If you're used to a certain flow of control, get ready for a jolt when you use finally.
A finally block of code can be defined after a try, as in:
try {  
	// do something  
}
finally {  
	// always do this, no matter what!  
}  
What do we mean by no matter what? Even if you break, return, or throw an exception in the try block, the finally code will always, and we mean always, be executed. Here's some code that illustrates how you might define a finally block:
class Tenacious { 
	
public static void main(String[] args) { 
  try { 
    myMethod1(); 
    myMethod2(); 
    myMethod3(); 
  }
  catch (Exception e) { 
    System.out.println("Catching exception"); 
  } 
} 
// ----- myMethod1()
static void myMethod1() { 
  try {
    return; 
  }
  finally { 
   System.out.println("Attempted Return"); 
 } 
} 
// ----- myMethod2()
static void myMethod2() { 
  top: 
   try { 
    break top; 
  }
  finally { 
    System.out.println("Attempted break"); 
  } // End Finally
} 
 // ----- myMethod3()
static void myMethod3() throws Exception { 
  try { 
    throw(new Exception()); 
  }
  finally { 
    System.out.println("Attempted to throw an exception"); 
  } 
 } 
} 
Here's the output:
 we tried to return  

 we tried to break  

 we tried to throw an exception  

 Catching exception 
Finally Keyword Quiz
This quiz pertains to the finally keyword previously discussed.
Finally Keyword Quiz
  Course navigation