Master Python Exception Handling: Propagation, Custom Errors, and Re‑throwing
This article explains Python exception propagation, demonstrates nested try blocks and function calls, shows how to define and raise custom exceptions, and illustrates re‑throwing exceptions within handlers, all backed by clear code examples and output screenshots.
Python Exception Propagation and Custom Exceptions
This article introduces Python exception handling, covering how exceptions propagate through nested try blocks and function calls, how to create and raise custom exceptions, and how to re‑throw exceptions inside handlers.
1. Exception Propagation
1.1 Try Nesting
import time
try:
f = open('test.txt')
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
finally:
f.close()
print('关闭文件')
except:
print("没有这个文件")
finally:
print("最后的finally")
# 这是test.txt文件中读取到信息Result:
1.2 Function Nesting
def test1():
print("----test1-1----")
print(num)
print("----test1-2----")
def test2():
print("----test2-1----")
test1()
print("----test2-2----")
def test3():
try:
print("----test3-1----")
test1()
print("----test3-2----")
except Exception as result:
print("捕获到了异常,信息是:%s" % result)
print("----test3-2----")
test3()
print("------华丽的分割线-----")
test2()Result:
Key points:
If a nested try block does not catch an exception, the exception propagates to the outer try block, which can then handle it; if still uncaught, it continues propagating.
When an exception occurs deep in a call chain (e.g., A→B→C), it bubbles up until a function catches it; if no function catches it, the default exception handling is invoked.
2. Raising Custom Exceptions
You can use the raise statement to trigger an exception. Custom exception classes should inherit from Exception or Error.
class ShortInputException(Exception):
'''自定义的异常类'''
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
def main():
try:
s = input('请输入 --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
except ShortInputException as result:
print('ShortInputException: 输入的长度是 %d,长度至少应是 %d' % (result.length, result.atleast))
else:
print('没有异常发生.')
main()Result:
Note: Calling super().__init__() in the subclass constructor is recommended to ensure proper initialization.
3. Raising Exceptions Inside Handlers
class Test(object):
def __init__(self, switch):
self.switch = switch # 开关
def calc(self, a, b):
try:
return a / b
except Exception as result:
if self.switch:
print("捕获开启,已经捕获到了异常,信息如下:")
print(result)
else:
raise
a = Test(True)
a.calc(11, 0)
print("----------------------华丽的分割线----------------")
a.switch = False
a.calc(11, 0)Result:
Conclusion
This article provides a detailed walkthrough of Python exception handling, including propagation mechanisms, custom exception creation, and re‑throwing strategies, supported by practical code snippets and output screenshots to help learners master exception management.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
