Finally Block in Java Programming

Finally Block in Java Programming

Previous Home Next

 

Finally is a keyword exceptional of try block.The code inside the finally block will always be executed. This is also 

true for cases when there is an exception or even executed return statement in the try block

In the finally block we usually have code that is used to perform clean up activities corresponding to the code in the try block. When an exception occurs in the try block control comes to the catch block and the rest of the code in the try block would not execute. In such cases we may need to have some code that cleans up the objects that we created/used in the try block.
 Syntax of Finally block



public void method() throws NoMatchedException
{
try {
//...
throw new Exception1();
//...
} catch ( Exception1 e ) {
// --- Handle the Exception1 here --
} catch ( Exception2 e ) {
// --- Handle the Exception2 here --
} finally {
// statements exicutes here if no exception occurs
}

 
public void method() throws NoMatchedException
{
try {
//...
throw new Exception1();
//...
} catch ( Exception1 e ) {
// --- Handle the Exception1 here --
} catch ( Exception2 e ) {
// --- Handle the Exception2 here --
} finally {
// statements exicutes here if no exception occurs
}

public void method() throws NoMatchedException
{
try {
//...
throw new Exception1();
//...
} catch ( Exception1 e ) {
// --- Handle the Exception1 here --
} catch ( Exception2 e ) {
// --- Handle the Exception2 here --
} finally {
// statements exicutes here if no exception occurs
}


Previous Home Next