天天看點

Python異常處理和程式調試

Table of Contents

​​1. Python中的異常​​

​​2. try...except使用​​

​​2.1 沒有捕獲​​

​​2.2 添加捕獲​​

​​3. try...except...finally​​

​​4. raise抛出異常​​

​​5. 自定義異常​​

​​6. assert斷言語句使用​​

1. Python中的異常

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

Python異常處理和程式調試

源碼:

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抛出異常

Python異常處理和程式調試
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. 自定義異常

Python異常處理和程式調試
Python異常處理和程式調試

結果:

Python異常處理和程式調試

6. assert斷言語句使用

Python異常處理和程式調試
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