`Finally` Block

Let's learn about the `finally` block and how to use it for handling exceptions.

We'll cover the following

A finally block contains a set of statements that are finally executed no matter how the program ended. This is generally used to free any resources that were used in the try..catch blocks of our program. Basically, the finally block contains the piece of program that is executed after the completion of both the Try and Catch blocks, regardless of whether an error occurred. The primary purpose of this block is to clean resources, like removing or disposing of objects used by the program from memory to make the memory free.

Powershell

PowerShell syntax:

Let’s understand the syntax of the finally block in Powershell.

try{
  # statements to be monitored for errors
}
catch{
  # handle errors here
}
finally{
  # final tasks: these are executed no matter if an error is thrown or not
}

Let’s take an example in PowerShell which we have discussed in the previous lesson. We will add a finally block to that example and will see that the finally block will always be executed.

Get hands-on with 1400+ tech skills courses.