本文转载自公众号《核心阅读》(ID:AI_Discovery)。写代码难免会出错,错误处理可以提前为这些错误做好准备。通常脚本会在发生错误时停止运行,但是通过错误处理脚本可以继续运行。为此,我们需要了解以下三个关键字:try:这是要运行的代码块,可能会出错。except:如果try块中出现错误,将执行此代码。finally:无论发生什么错误,这段代码都必须执行。现在,我们定义了一个将两个数字相加的函数“求和”。该功能工作正常。>>>defsummation(num1,num2):print(num1+num2)>>>summation(2,3)5接下来,我们让用户输入其中一个数字并运行函数。>>>num1=2>>>num2=input("Enternumber:")Enternumber:3>>>summation(num1,num2)>>>print("这一行因为错误不会打印")------------------------------------------------------------------------TypeErrorTraceback(mostrecentcalllast)in---->1summation(num1,num2)2print("Thislinewillnotbeprintedbecauseoftheerror")insummation(num1,num2)1defsummation(num1,num2):---->2print(num1+num2)TypeError:unsupportedoperandtype(s)for+:intandstr发生“TypeError”错误,因为我们尝试添加数字和字符串。注意,错误发生后,下面的代码将不会执行。所以我们需要使用上面提到的关键字来保证即使出现问题,脚本仍然运行。>>try:summed=2+3except:print("Summationisnotofthesametype")Summationisnotofthesametype可以看到try块出现了错误,except块的代码开始运行,打印语句。接下来添加一个“else”块来处理没有错误发生的情况。>>>try:summed=2+3except:print("Summationisnotofthesametype")else:print("Therewasnoerrorandresultis:",summed)Therewasnoerrorandresultis:5接下来我们再用一个例子来理解。在此示例中,我们还在except块中指示错误类型。如果没有标记错误类型,则将对所有异常执行except块。>>>try:f=open(test,w)f.write("Thisatestfile")exceptTypeError:print("Thereisatypeerror")exceptOSError:print("ThereisanOSerror")finally:print("Thiswillprintevenifnoerror")Thiswillprintevenifnoerror现在,故意创建报错,看看except块是否和finally块一起工作!>>>尝试:f=open(test,r)f.write("Thisatestfile")exceptTypeError:print("Thereisatypeerror")exceptOSError:print("ThereisanOSerror")finally:print("Thiswillprintevenifnoerror")ThereisanOSerrorThiswillprintevenifnoerror