Using Try-Except and Finally Blocks

Tutorial 2 of 5

1. Introduction

Goal of the Tutorial

This tutorial aims to teach the essentials of using try-except and finally blocks in Python, which are indispensable tools for handling exceptions and ensuring your programs run smoothly, even when encountering unexpected errors.

Learning Outcomes

By the end of this tutorial, you'll understand:
- What try-except blocks are
- How to use try-except blocks
- What the finally block is
- How to use the finally block

Prerequisites

A basic understanding of Python programming is necessary. Familiarity with the concept of errors and exceptions in Python might be helpful but is not required.

2. Step-by-Step Guide

What are Try-Except Blocks?

In Python, the try-except block is used to catch and handle exceptions. Python executes the code following the 'try' keyword. If a problem occurs, it raises an exception. The code following the 'except' keyword is the program's response to any exceptions.

How to Use Try-Except Blocks

The syntax of try-except block is:

try:
   # code that may raise an exception
except ExceptionType:
   # code that will execute if the exception is raised

If the code inside the 'try' block throws an exception mentioned in the 'except' block, the 'except' block code will be executed, and the program will continue to run.

What is the Finally Block?

The finally block is optional and used for cleaning up actions, like closing files. The code inside the 'finally' block will be executed regardless of whether an exception occurred.

How to Use the Finally Block

The syntax of finally block is:

try:
   # code that may raise an exception
except ExceptionType:
   # code that will execute if the exception is raised
finally:
   # code that will execute no matter what

3. Code Examples

Example 1: Simple Try-Except Block

try:
    x = 1 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
    x = 0
    print("Divided by zero, so I set x to 0.")

Here, we're attempting to divide 1 by 0, which causes a ZeroDivisionError. The except block catches this exception and sets x to 0, then prints a message.

Example 2: Try-Except-Finally Block

try:
    file = open("example.txt", "r") # This will raise a FileNotFoundError if the file doesn't exist
except FileNotFoundError:
    print("File not found. Please make sure the file exists.")
finally:
    file.close()
    print("File closed.")

In this case, we're trying to open a file that may not exist. The except block will catch a FileNotFoundError and print a message. The finally block will close the file and print a confirmation, regardless of whether an exception was raised.

4. Summary

In this tutorial, we learned how to use try-except and finally blocks in Python to handle exceptions and perform cleanup tasks. These tools are crucial for writing robust, error-resilient programs.

5. Practice Exercises

  1. Write a program that asks the user for an integer and prints the square of it. Use a try-except block to catch a ValueError if the user doesn't enter an integer.

Solution:

try:
    number = int(input("Enter a number: "))
    print("The square of the number is", number**2)
except ValueError:
    print("That's not a valid number!")
  1. Modify the program above to include a finally block that prints "End of program" when the program finishes.

Solution:

try:
    number = int(input("Enter a number: "))
    print("The square of the number is", number**2)
except ValueError:
    print("That's not a valid number!")
finally:
    print("End of program.")

Continue practicing by creating more complex scenarios and using different types of exceptions. This will help you become more comfortable with using try-except and finally blocks in Python.