Python Try Except

When writing Python code, errors can be frustrating. Luckily, Python’s try and except blocks provide an effective way to manage errors without breaking the flow of your code. The try and except statements let you handle specific exceptions, print error messages, and even use else and finally blocks for more…

When writing Python code, errors can be frustrating. Luckily, Python’s try and except blocks provide an effective way to manage errors without breaking the flow of your code. The try and except statements let you handle specific exceptions, print error messages, and even use else and finally blocks for more control.

In this guide, we’ll explore how to use try, except, else, and finally effectively to write robust and error-tolerant Python code.

What Is try and except in Python?

In Python, try and except are used to catch and handle exceptions, allowing your program to continue executing or provide custom error messages rather than crashing. Here’s a basic syntax for using try and except:

try:
    # Code that might raise an exception
except SomeException:
    # Code to run if the exception occurs

Example Usage

Let’s look at a simple example to handle division by zero:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:

Cannot divide by zero!

In this example, the try block contains code that could potentially raise a ZeroDivisionError. When this error occurs, the code in the except block runs, printing a helpful message.

Catching Specific Exceptions in Python

In Python, you can catch specific exceptions to handle different error types individually. This allows you to create custom responses for each error type and manage multiple errors gracefully.

try:
    value = int("abc")
except ValueError:
    print("Invalid number format!")
except TypeError:
    print("Unsupported operation!")

Output:

Invalid number format!

Here, try and except are used to handle a ValueError (raised by trying to convert a string to an integer) with a custom error message. You can add as many specific except blocks as needed.

Using try and except with else

In Python, the else block is used with try and except to define code that runs only if no exceptions occur in the try block. This is helpful when you want to perform certain actions only when the code in the try block is successful.

try:
    number = int("42")
except ValueError:
    print("Conversion failed!")
else:
    print("Conversion successful:", number)

Output:

Conversion successful: 42

In this example, else only runs if the try block completes without error. If an exception occurs, the else block is skipped.

Printing Errors in Python Try Except

Sometimes, you want to print the exact error message rather than a generic one. Python’s except block allows you to capture the error message using the as keyword.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error occurred: {e}")

Output:

Error occurred: division by zero

By using as e, you can access the exception message, which provides specific details about the error that occurred.

Using try, except, and finally in Python

The finally block runs regardless of whether an exception occurs or not. This is useful for cleanup tasks, such as closing files or releasing resources, that need to happen regardless of success or failure.

try:
    file = open("sample.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    file.close()
    print("File closed.")

Output:

File not found!
File closed.

In this example, the finally block closes the file, ensuring the resource is released even if an error occurs. The finally block is a helpful way to maintain resource integrity in your programs.

Practical Examples of Using try, except, else, and finally

Example 1: Handling Multiple Exceptions

Here’s an example of using try, except, else, and finally to handle multiple exceptions in a single block:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
    print("You cannot divide by zero!")
else:
    print("Division successful! Result is:", result)
finally:
    print("Program execution completed.")

Output if the user enters “0”:

You cannot divide by zero!
Program execution completed.

Output if the user enters “abc”:

Invalid input! Please enter a numeric value.
Program execution completed.

In this example:

  • try contains code that could raise a ValueError or ZeroDivisionError.
  • except catches these errors separately and provides specific error messages.
  • else only runs if no exception occurs, and finally always runs, printing a completion message.

Example 2: Using try, except, and finally with Resource Management

When working with files, databases, or network connections, try, except, and finally are invaluable for ensuring resources are properly closed, even if errors occur.

try:
    with open("data.txt", "r") as file:
        data = file.read()
except FileNotFoundError as e:
    print(f"Error: {e}")
else:
    print("File content successfully read!")
finally:
    print("Resource handling complete.")

Output:

Error: [Errno 2] No such file or directory: 'data.txt'
Resource handling complete.

Using with open automatically closes the file after reading, but the finally block provides a good spot for additional cleanup or logging.

Conclusion

The try and except blocks in Python help you gracefully handle errors, while the else and finally blocks provide more control over your code’s flow. Here’s a quick recap of each component:

  • try: Contains the code that might raise an exception.
  • except: Catches and handles specific exceptions, letting you respond to errors.
  • else: Runs if no exceptions occur, useful for actions that rely on the success of try.
  • finally: Runs regardless of success or failure, ideal for cleanup actions.

Mastering try, except, else, and finally will help you write Python code that’s resilient and easier to troubleshoot, improving the overall quality of your programs.

Want to advance your Python programming skills? Enroll in our Python course by clicking the link below:

Free Course: Python 3 for Beginners

Python is one of the most used programming languages in the world. Both the popularity and the deman…

50 Lessons
1 Quizzes
1 Labs
5 Hr

Now that you know the basics, try incorporating try and except in your own projects to see how it simplifies error handling and keeps your code running smoothly.

CREATE YOUR FREE ACCOUNT & GET OUR

FREE IT LABS

profile avatar

Paul Hill

Paul Hill is the founder of ServerAcademy.com and IT instructor to over 500,000 students online!
0 0 votes
Lesson Rating
Subscribe
Notify of
profile avatar
0 Comments
Inline Feedbacks
View all comments