Python异常处理和程序调试
原创
©著作权归作者所有:来自51CTO博客作者JDSH0224的原创作品,请联系作者获取转载授权,否则将追究法律责任
Table of Contents
1. Python中的异常
2. try...except使用
2.1 没有捕获
2.2 添加捕获
3. try...except...finally
4. raise抛出异常
5. 自定义异常
6. assert断言语句使用
1. Python中的异常
2. try...except使用
2.1 没有捕获
#try:
open("hello.txt")
#except FileNotFoundError:
print("file not found")
#except:
print("Program abort")
调试信息(程序异常退出):
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
File "E:/python/python project/hello world.py", line 4
open("hello.txt")
^
IndentationError: unexpected indent
Process finished with exit code 1
2.2 添加捕获
try:
open("hello.txt")
except FileNotFoundError:
print("file not found")
except:
print("Program abort")
try:
result = 10/0
except ZeroDivisionError:
print("0 is division error")
else:
print("resule=%d" % result)
调试信息(程序捕获到信息并能够正常运行):
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
file not found
0 is division error
3. try...except...finally
源码:
try:
f = open("hello.txt", "r")
except FileNotFoundError:
print("File not found")
except:
print("Program abort")
finally:
print("Exec finally, Close fd")
f.close()
结果:
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
Traceback (most recent call last):
file not found
File "E:/python/python project/hello world.py", line 25, in <module>
0 is division error
f.close()
NameError: name 'f' is not defined
File not found
Exec finally, Close fd
Process finished with exit code 1
4. raise抛出异常
try:
s = None
if s is None:
print("s is None")
raise NameError
print(len(s))
except TypeError:
print("Null object is no length")
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
s is None
Traceback (most recent call last):
File "E:/python/python project/hello world.py", line 7, in <module>
raise NameError
NameError
Process finished with exit code 1
5. 自定义异常
结果:
6. assert断言语句使用
t = "hello"
assert len(t) > 1
t = "hello"
assert len(t) == 1
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
Traceback (most recent call last):
File "E:/python/python project/hello world.py", line 7, in <module>
assert len(t) == 1
AssertionError
Process finished with exit code 1