Web Analytics

Finally Block

Intermediate ~10 min read

The finally block lets you execute code, subsequent to a try...catch block, regardless of whether an exception is handled or not.

Syntax

try {
  //  Block of code to try
}
catch(Exception e) {
  //  Block of code to handle errors
}
finally {
  //  Code to be executed regardless of the result
}

Why use it?

It is mostly used for "Cleanup Code", such as closing files, closing database connections, or releasing other resources that must be closed whether the operation succeeded or failed.

Example

Output
Click Run to execute your code

Summary

  • The finally block always executes.
  • It runs after try and catch blocks.
  • Useful for closing resources (File Streams, DB connections).