Handling Exceptions Using Try and Catch

Learn how to handle exceptions by using Try and Catch blocks.

We'll cover the following

The way exception handling works is relatively consistent across programming languages. First, we attempt to execute a section of the program in a try block. If it throws an error, we can handle it in a catch block and, at last, perform some final mandatory steps in the finally block. Let us look into each of these blocks in detail one at a time.

Try Block

The 'try' block defines a section of code that we want the programming language to monitor for any errors or exceptions. The following is the PowerShell syntax for the try block:

try{
  # statements
}

Python syntax is similar except for a colon (:) after the try keyword and an indentation instead of curly brackets { }.

try:
  # statements

Catch and Except Block

When an error occurs in a try block, the PowerShell scripts search for a catch block to handle that error. A catch block has a list of statements to handle the failure or to recover from the error that was caught in the try block.

Get hands-on with 1200+ tech skills courses.