[Python]B08─除错(debug)

Hi! 大家好,我是Eric,这次教大家Python的除错(debug)!
http://img2.58codes.com/2024/emoticon32.gif


■ 除错(debug)

■ coding时遇到错误通常可分为3大类

语法错误(syntax error),程式码不符合程式规定的语法执行时错误(runtime error),可能是由于使用者输入错误导致语意错误(semantic error),可能是逻辑上的错误,执行并没有问题,一般较难追蹤与修改

■ 执⾏时错误。以下为常见的错误:

print(Q)     #使用未定义的变数1 + 'abc'    #使用未定义的操作2 / 0)       #尝试数学上不合法计算L[1,2,3]     #尝试访问不存在的元素L[1000]

■ 捕获异常:try 和 except

补获运行时异常的工具是try与except
try:                 # 当一个错误在try语句中发生,之后except语句才会被执行     print("let's try something:")     x = 1 / 0    # ZeroDivisionErrorexcept:     print("something bad happened!")def safe_divide(a, b):     # 当输入呈现被除零异常时,将会进行捕获,只能捕获被除零异常     try:        return a / b     except ZeroDivisionError:        return 1E100safe_divide(1, 0)safe_divide(1, '2')
投掷异常:raise。可透过raise语句自己投掷异常
raise RuntimeError("my error message")
自定义的fibonacci 函式,潜在问题是输入负数,所以我们可以投掷ValueError("N must be non-negative"),告诉使用者输入一个负数是不被接受的
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)  
现在使用者能够确切知道甚么输入是无效的,可用try...except来处理
N = -10try:     print("trying this...")     print(fibonacci(N))except ValueError:     print("Bad value: need to do something else")

■ 深入探究异常

访问错误资讯,在try...except语句中,处理错误信息本身,可以使用as关键字
try:    x = 1 / 0except ZeroDivisionError as err:    print("Error class is: ", type(err))    print("Error message is:", err)
定义自定义异常,除了内建异常型别外,可以透过类别继承来自定义异常,定义一个特殊的ValueError
class MySpecialError(ValueError):      passraise MySpecialError("here's the message")
现这将允许你使⽤只能捕获此类别错误的 try...except 区块
try:     print("do something")     raise MySpecialError("[informative error message here]")except MySpecialError:     print("do something else")

■ try...except...else...finally

除了try...except之外,也可以使用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")
Refer to《Python 旋风之旅,[正体中文]Will保哥》的第6章

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章