1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+ """
4+ 异常处理基础 - Exception Basics
5+
6+ 本模块演示Python异常处理的基本概念:
7+ 1. 什么是异常
8+ 2. 常见的内置异常类型
9+ 3. 异常的层次结构
10+ 4. 基本的异常处理语法
11+ 5. 异常信息的获取和显示
12+
13+ 作者: Python学习教程
14+ 日期: 2024
15+ """
16+
17+ import sys
18+ import traceback
19+
20+
21+ def demonstrate_common_exceptions ():
22+ """
23+ 演示常见的Python内置异常类型
24+ """
25+ print ("=" * 50 )
26+ print ("常见异常类型演示" )
27+ print ("=" * 50 )
28+
29+ # 1. NameError - 使用未定义的变量
30+ print ("\n 1. NameError - 使用未定义的变量:" )
31+ try :
32+ print (undefined_variable ) # 这会引发NameError
33+ except NameError as e :
34+ print (f"捕获到NameError: { e } " )
35+ print (f"异常类型: { type (e ).__name__ } " )
36+
37+ # 2. TypeError - 类型错误
38+ print ("\n 2. TypeError - 类型错误:" )
39+ try :
40+ result = "hello" + 5 # 字符串和数字不能直接相加
41+ except TypeError as e :
42+ print (f"捕获到TypeError: { e } " )
43+ print (f"异常类型: { type (e ).__name__ } " )
44+
45+ # 3. ValueError - 值错误
46+ print ("\n 3. ValueError - 值错误:" )
47+ try :
48+ number = int ("hello" ) # 无法将"hello"转换为整数
49+ except ValueError as e :
50+ print (f"捕获到ValueError: { e } " )
51+ print (f"异常类型: { type (e ).__name__ } " )
52+
53+ # 4. IndexError - 索引错误
54+ print ("\n 4. IndexError - 索引错误:" )
55+ try :
56+ my_list = [1 , 2 , 3 ]
57+ print (my_list [10 ]) # 索引超出范围
58+ except IndexError as e :
59+ print (f"捕获到IndexError: { e } " )
60+ print (f"异常类型: { type (e ).__name__ } " )
61+
62+ # 5. KeyError - 键错误
63+ print ("\n 5. KeyError - 键错误:" )
64+ try :
65+ my_dict = {"name" : "Alice" , "age" : 25 }
66+ print (my_dict ["height" ]) # 键不存在
67+ except KeyError as e :
68+ print (f"捕获到KeyError: { e } " )
69+ print (f"异常类型: { type (e ).__name__ } " )
70+
71+ # 6. ZeroDivisionError - 除零错误
72+ print ("\n 6. ZeroDivisionError - 除零错误:" )
73+ try :
74+ result = 10 / 0 # 除以零
75+ except ZeroDivisionError as e :
76+ print (f"捕获到ZeroDivisionError: { e } " )
77+ print (f"异常类型: { type (e ).__name__ } " )
78+
79+ # 7. FileNotFoundError - 文件未找到错误
80+ print ("\n 7. FileNotFoundError - 文件未找到错误:" )
81+ try :
82+ with open ("nonexistent_file.txt" , "r" ) as f :
83+ content = f .read ()
84+ except FileNotFoundError as e :
85+ print (f"捕获到FileNotFoundError: { e } " )
86+ print (f"异常类型: { type (e ).__name__ } " )
87+
88+ # 8. AttributeError - 属性错误
89+ print ("\n 8. AttributeError - 属性错误:" )
90+ try :
91+ my_string = "hello"
92+ my_string .nonexistent_method () # 字符串没有这个方法
93+ except AttributeError as e :
94+ print (f"捕获到AttributeError: { e } " )
95+ print (f"异常类型: { type (e ).__name__ } " )
96+
97+
98+ def demonstrate_exception_hierarchy ():
99+ """
100+ 演示Python异常的层次结构
101+ """
102+ print ("\n " + "=" * 50 )
103+ print ("Python异常层次结构" )
104+ print ("=" * 50 )
105+
106+ # 显示一些重要异常类的继承关系
107+ exceptions_to_check = [
108+ Exception ,
109+ ArithmeticError ,
110+ ZeroDivisionError ,
111+ LookupError ,
112+ IndexError ,
113+ KeyError ,
114+ ValueError ,
115+ TypeError ,
116+ NameError ,
117+ AttributeError ,
118+ FileNotFoundError ,
119+ IOError ,
120+ OSError
121+ ]
122+
123+ print ("\n 异常类的继承关系:" )
124+ for exc_class in exceptions_to_check :
125+ mro = exc_class .__mro__ # Method Resolution Order
126+ hierarchy = " -> " .join ([cls .__name__ for cls in mro ])
127+ print (f"{ exc_class .__name__ } : { hierarchy } " )
128+
129+ # 演示异常捕获的顺序重要性
130+ print ("\n 异常捕获顺序的重要性:" )
131+ try :
132+ # 这会引发ZeroDivisionError
133+ result = 10 / 0
134+ except ArithmeticError as e :
135+ print (f"被ArithmeticError捕获: { e } " )
136+ print (f"实际异常类型: { type (e ).__name__ } " )
137+ print ("注意: ZeroDivisionError是ArithmeticError的子类" )
138+
139+
140+ def demonstrate_basic_exception_handling ():
141+ """
142+ 演示基本的异常处理语法
143+ """
144+ print ("\n " + "=" * 50 )
145+ print ("基本异常处理语法" )
146+ print ("=" * 50 )
147+
148+ # 1. 基本的try-except
149+ print ("\n 1. 基本的try-except:" )
150+ try :
151+ number = int (input ("请输入一个数字 (或直接按回车使用默认值): " ) or "42" )
152+ result = 100 / number
153+ print (f"100 / { number } = { result } " )
154+ except ValueError :
155+ print ("输入的不是有效数字!" )
156+ except ZeroDivisionError :
157+ print ("不能除以零!" )
158+
159+ # 2. 捕获异常对象
160+ print ("\n 2. 捕获异常对象获取详细信息:" )
161+ try :
162+ my_list = [1 , 2 , 3 ]
163+ index = int (input ("请输入列表索引 (或直接按回车使用默认值): " ) or "10" )
164+ print (f"列表元素: { my_list [index ]} " )
165+ except (ValueError , IndexError ) as e :
166+ print (f"发生错误: { e } " )
167+ print (f"错误类型: { type (e ).__name__ } " )
168+ print (f"错误参数: { e .args } " )
169+
170+ # 3. 捕获所有异常
171+ print ("\n 3. 捕获所有异常 (不推荐在生产代码中使用):" )
172+ try :
173+ # 模拟一个可能出错的操作
174+ operation = input ("输入一个Python表达式 (或直接按回车): " ) or "1/0"
175+ result = eval (operation ) # 注意: eval在实际项目中要谨慎使用
176+ print (f"结果: { result } " )
177+ except Exception as e :
178+ print (f"捕获到异常: { e } " )
179+ print (f"异常类型: { type (e ).__name__ } " )
180+
181+
182+ def demonstrate_exception_information ():
183+ """
184+ 演示如何获取和显示异常信息
185+ """
186+ print ("\n " + "=" * 50 )
187+ print ("异常信息获取和显示" )
188+ print ("=" * 50 )
189+
190+ try :
191+ # 创建一个会引发异常的情况
192+ data = {"users" : [{"name" : "Alice" , "age" : 25 }]}
193+ user_id = 5 # 不存在的用户ID
194+ user_name = data ["users" ][user_id ]["name" ]
195+ except Exception as e :
196+ print ("\n 异常信息详解:" )
197+ print (f"1. 异常类型: { type (e ).__name__ } " )
198+ print (f"2. 异常消息: { str (e )} " )
199+ print (f"3. 异常参数: { e .args } " )
200+
201+ # 获取异常的详细信息
202+ exc_type , exc_value , exc_traceback = sys .exc_info ()
203+ print (f"\n 4. 系统异常信息:" )
204+ print (f" 异常类型: { exc_type .__name__ } " )
205+ print (f" 异常值: { exc_value } " )
206+
207+ # 打印完整的traceback
208+ print ("\n 5. 完整的异常追踪:" )
209+ traceback .print_exc ()
210+
211+ # 格式化traceback为字符串
212+ print ("\n 6. 格式化的异常追踪:" )
213+ tb_str = traceback .format_exc ()
214+ print (tb_str )
215+
216+
217+ def safe_division (a , b ):
218+ """
219+ 安全除法函数 - 演示异常处理的实际应用
220+
221+ Args:
222+ a: 被除数
223+ b: 除数
224+
225+ Returns:
226+ 除法结果或错误信息
227+ """
228+ try :
229+ # 尝试进行除法运算
230+ result = a / b
231+ return {"success" : True , "result" : result , "message" : "计算成功" }
232+ except ZeroDivisionError :
233+ return {"success" : False , "result" : None , "message" : "错误: 除数不能为零" }
234+ except TypeError as e :
235+ return {"success" : False , "result" : None , "message" : f"错误: 参数类型不正确 - { e } " }
236+ except Exception as e :
237+ return {"success" : False , "result" : None , "message" : f"未知错误: { e } " }
238+
239+
240+ def demonstrate_practical_example ():
241+ """
242+ 演示异常处理的实际应用示例
243+ """
244+ print ("\n " + "=" * 50 )
245+ print ("实际应用示例 - 安全除法函数" )
246+ print ("=" * 50 )
247+
248+ # 测试不同的输入情况
249+ test_cases = [
250+ (10 , 2 ), # 正常情况
251+ (10 , 0 ), # 除零错误
252+ ("10" , 2 ), # 类型错误
253+ (10 , "abc" ), # 类型错误
254+ (10 , None ), # 类型错误
255+ ]
256+
257+ for i , (a , b ) in enumerate (test_cases , 1 ):
258+ print (f"\n 测试 { i } : safe_division({ a } , { b } )" )
259+ result = safe_division (a , b )
260+
261+ if result ["success" ]:
262+ print (f"✅ { result ['message' ]} : { result ['result' ]} " )
263+ else :
264+ print (f"❌ { result ['message' ]} " )
265+
266+
267+ def main ():
268+ """
269+ 主函数 - 运行所有演示
270+ """
271+ print ("Python异常处理基础教程" )
272+ print ("=" * 60 )
273+
274+ try :
275+ # 运行各个演示函数
276+ demonstrate_common_exceptions ()
277+ demonstrate_exception_hierarchy ()
278+ demonstrate_basic_exception_handling ()
279+ demonstrate_exception_information ()
280+ demonstrate_practical_example ()
281+
282+ print ("\n " + "=" * 60 )
283+ print ("🎉 异常处理基础教程完成!" )
284+ print ("\n 📚 学习要点总结:" )
285+ print ("1. 异常是程序运行时发生的错误" )
286+ print ("2. Python有丰富的内置异常类型" )
287+ print ("3. 异常有层次结构,子类异常会被父类捕获" )
288+ print ("4. 使用try-except可以优雅地处理异常" )
289+ print ("5. 可以获取异常的详细信息用于调试" )
290+ print ("6. 异常处理让程序更加健壮和用户友好" )
291+
292+ print ("\n ➡️ 下一步学习: 02_try_except.py - 深入学习try-except语法" )
293+
294+ except KeyboardInterrupt :
295+ print ("\n \n 程序被用户中断" )
296+ except Exception as e :
297+ print (f"\n 程序执行出错: { e } " )
298+ traceback .print_exc ()
299+
300+
301+ if __name__ == "__main__" :
302+ main ()
0 commit comments