Hi! 大家好,我是Eric,這次教大家Python的除錯(debug)!
■ coding時遇到錯誤通常可分為3大類
■ 執⾏時錯誤。以下為常見的錯誤:
print(Q) #使用未定義的變數
1 + 'abc' #使用未定義的操作
2 / 0) #嘗試數學上不合法計算
L[1,2,3] #嘗試訪問不存在的元素
L[1000]
■ 捕獲異常:try 和 except
try: # 當一個錯誤在try語句中發生,之後except語句才會被執行
print("let's try something:")
x = 1 / 0 # ZeroDivisionError
except:
print("something bad happened!")
def safe_divide(a, b): # 當輸入呈現被除零異常時,將會進行捕獲,只能捕獲被除零異常
try:
return a / b
except ZeroDivisionError:
return 1E100
safe_divide(1, 0)
safe_divide(1, '2')
raise RuntimeError("my error message")
def fibonacci(N):
if N < 0:
raise ValueError("N must be non-negative")
L = []
a, b = 0, 1
while len(L) < N:
a, b = b, a + b
L.append(a)
return L
fibonacci(-10)
N = -10
try:
print("trying this...")
print(fibonacci(N))
except ValueError:
print("Bad value: need to do something else")
■ 深入探究異常
try:
x = 1 / 0
except ZeroDivisionError as err:
print("Error class is: ", type(err))
print("Error message is:", err)
class MySpecialError(ValueError):
pass
raise MySpecialError("here's the message")
try:
print("do something")
raise MySpecialError("[informative error message here]")
except MySpecialError:
print("do something else")
■ try...except...else...finally
try:
print("try something here")
except:
print("this happens only if it fails")
else:
print("this happens only if it succeeds")
finally:
print("this happens no matter what")