Handling Exceptions with Try-Except

Tutorial 3 of 5

Handling Exceptions with Try-Except

1. Introduction

1.1 Brief Explanation of the Tutorial's Goal

In this tutorial, you will learn about exception handling in Python, focusing on how to use try-except blocks. Exception handling is crucial for writing sturdy, fault-tolerant code that can gracefully handle runtime errors.

1.2 What You Will Learn

You will learn:
- What exceptions are in Python
- How to use try-except blocks to handle exceptions
- The different types of exceptions
- How to handle multiple exceptions

1.3 Prerequisites

Basic knowledge of Python is required. Familiarity with control flow (if-else statements, for loops, while loops) is beneficial.

2. Step-by-Step Guide

2.1 Exceptions in Python

An exception is an event that occurs during the execution of a program, disrupting the normal flow of the program's instructions. This event is typically due to an error.

2.2 Try-Except Blocks

A try-except block in Python is used to catch and handle exceptions. Python executes code following the try keyword as a "normal" part of the program. If an exception occurs, the code under try is skipped, and the code under except is executed.

2.3 Handling Multiple Exceptions

You can handle multiple exceptions by using multiple except blocks. Each except block handles a specific exception type.

3. Code Examples

3.1 Basic Try-Except Block

try:
    # this code is executed first
    x = 5 / 0
except:
    # this code is executed if there is an exception
    print("An error occurred")

In this example, we try to divide by zero, which raises a ZeroDivisionError. Since it's inside a try block, the error is caught and the program prints "An error occurred" instead of crashing.

3.2 Handling Specific Exceptions

try:
    # this code is executed first
    x = 5 / 0
except ZeroDivisionError:
    # this code is executed if there is a ZeroDivisionError
    print("Tried to divide by zero")

Here, we specify the exception type in the except keyword. This block will only catch ZeroDivisionError exceptions.

4. Summary

In this tutorial, we learned about exceptions in Python and how to handle them using try-except blocks. We also covered how to handle multiple exceptions using multiple except blocks.

5. Practice Exercises

5.1 Exercise 1

Write a program that asks the user for an integer and prints the square of it. Use a while loop with a try-except block to account for incorrect inputs.

5.2 Exercise 2

Write a function that accepts two numbers and divides them. Use a try-except block to catch any potential exceptions.

6. Additional Resources