Finally Block
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
finallyblock always executes. - It runs after
tryandcatchblocks. - Useful for closing resources (File Streams, DB connections).
Enjoying these tutorials?