Fundamentals 7 min read

Master Python Exception Handling: Real-World Examples and Best Practices

This article introduces Python exception handling fundamentals, demonstrating how to catch, manage, and retrieve error information with practical code examples—including try/except, multiple exceptions, else, finally blocks—and explains their behavior in real-world development scenarios.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Exception Handling: Real-World Examples and Best Practices

Python Exception Handling Overview

When Python encounters an error, the interpreter cannot continue and raises an exception, providing an error message.

2. Example Analysis

Attempting to open a non‑existent file 123.txt raises an IOError ("No such file or directory").

print('-----test--1---')
open('123.txt','r')
print('-----test--2---')

Result:

<1> Catching Exceptions with try...except...

Example:

try:
    print('-----test--1---')
    open('123.txt','r')
    print('-----test--2---')
except IOError:
    pass

Result:

Explanation:

The program shows no error because the IOError is caught. pass does nothing; replacing it with print would display a message.

Summary:

Place code that may raise an error inside try.

Handle the exception inside except.

<2> Catching Multiple Exceptions

Example:

try:
    print(num)
except IOError:
    print('产生错误了')

Result:

Why does the program still show an error message even though an except block is present?

Answer: The except catches IOError, but the raised exception is NameError, so it is not handled.

Corrected code:

try:
    print(num)
except NameError:
    print('产生错误了')

Result:

In practice, multiple exceptions can be caught with a tuple:

#coding=utf-8
try:
    print('-----test--1---')
    open('123.txt','r')  # IOError if file missing
    print('-----test--2---')
    print(num)  # NameError if undefined
except (IOError, NameError):
    # handle both exceptions
    pass

Note: When catching multiple exceptions, list their names in a tuple after except.

<3> Accessing Exception Information

try:
    open("a.txt")
except (NameError, IOError) as result:
    print("捕抓到异常")
    print("信息展示:", result)

Result:

<4> Catching All Exceptions

try:
    open("a.txt")
except Exception as result:
    print("捕抓到异常")
    print("信息展示:", result)

Result:

<5> Using else with try...except

The else block runs when no exception is raised.

try:
    num = 100
    print(num)
except NameError as errorMsg:
    print('产生错误了:%s' % errorMsg)
else:
    print('没有捕获到异常,真高兴')

Result:

<6> try...finally...

The finally clause executes regardless of whether an exception occurs, useful for cleanup such as closing files.

import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except:
        # handle read errors, e.g., Ctrl+C
        pass
    finally:
        f.close()
        print('关闭文件')
except:
    print("没有这个文件")

Result:

Explanation: The script reads each line of test.txt, pauses 2 seconds before printing, and demonstrates that a KeyboardInterrupt triggers, but the finally block still runs to close the file.

Conclusion

This article explained Python exception fundamentals, covering common exception handling techniques with rich examples to help readers understand basic operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonError Handlingcoding tutorialtry-except
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.