Python Tutorial: Try Else

beginner
5 min

Python Tutorial: Try Else

Welcome to the Try Else lesson! In this tutorial, we'll learn about the try-else statement in Python, a powerful tool for managing error handling and flow control. Let's get started! 🎯

What is the try-else statement?

The try-else statement in Python is a control flow structure that allows you to test for exceptions (errors) and execute code both when an exception occurs and when it doesn't. This is particularly useful for handling complex scenarios where you need to make decisions based on whether an error occurred or not. 💡

Basic try-else structure

A basic try-else structure consists of three parts:

  1. try: The code block where you write the code that may raise an exception.
  2. except: The code block where you write the code that will be executed when an exception occurs.
  3. else: The code block that will be executed if no exception occurs while executing the try block.

Let's see a simple example:

python
try: print(5 / 0) except ZeroDivisionError: print("Cannot divide by zero.") else: print("No exception occurred.")

In this example, we're trying to divide by zero, which raises a ZeroDivisionError. The code within the except block handles the exception, and the code within the else block is executed only if no exception occurs.

Try-else with multiple exceptions

If you want to handle multiple exceptions, you can list them in the except clause, separated by commas. The interpreter will go through the listed exceptions in order until it finds the one that matches the exception raised.

python
try: file = open("non_existent_file.txt", "r") except FileNotFoundError: print("The specified file doesn't exist.") except Exception as e: print(f"An error occurred: {e}")

In this example, we're trying to open a file that doesn't exist. The first exception we're handling is FileNotFoundError. If for some reason another exception occurs, it will be caught by the second except block.

Nested try-else statements

You can also nest try-else statements to handle complex scenarios involving multiple layers of error handling.

python
try: x = int(input("Enter a number: ")) y = int(input("Enter another number: ")) result = x / y except ValueError: print("You need to enter numbers.") except ZeroDivisionError: print("Cannot divide by zero.") else: print("The result is:", result)

In this example, we're first trying to get input from the user. If the user enters something that's not a number, a ValueError is raised. If the user enters zero as the second number, a ZeroDivisionError is raised. Otherwise, we calculate the result and print it.

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `try-else` statement in Python?

That's it for today! We've learned about the try-else statement in Python and how to use it for error handling and flow control. In the next lesson, we'll dive deeper into exception handling. 📝

Happy coding! ✅