Java Keyword Finally

The reserved keyword finally is used to define a block of Java code statements for a block defined previously by the try keyword. The finally block is executed after execution exits the try block and after any catch clauses regardless of whether an exception was thrown or caught.

Let’s take a gander at the syntax declaration of finally within the confines of a try/catch block.

//JavaCodeDepot Sample 

try {
    //If an exception is thrown in here
} catch (some exception) {
    //Catch the exception that was thrown
} finally {
    //The finally block is always executed. Good time for cleanup.

Check out the sample code below that tries to copy one file to another with nested catch statements followed by the finally block.

// Sample

//Define our input and out file objects
boolean fileFound;
File sourceFile = new File("C:\\Users\\Admin\\Documents\\Java\\file1.txt");
File destinationFile = new File("C:\\Users\\Admin\\Documents\\Java\\file2.txt");
try {
     Files.copy(sourceFile.toPath(), destinationFile.toPath());
catch(FileNotFoundException fnfe) 
    System.out.println("FileNotFoundException: "+fnfe.toString());
catch(Exception ex) 
     System.out.println("Exception: "+ex.toString());
finally {
   fileFound = false;

You should note that the finally block within the try/catch block is an optional piece of code.

The complete list of Java reserved keywords contains a total of 50 keywords and 3 literal words that are unable to be used as variable names.

Add a Comment

Your email address will not be published. Required fields are marked *