您的位置:首页 > 编程语言 > Python开发

python异常处理

2017-07-28 22:08 295 查看
异常处理机制的引入:如果处理错误或特殊情况的分支语句过多,那么处理正常情况的主程序就会变得不清晰易读。

Python使用try…except…来进行异常处理,基本

格式如下:try:

body

except ErrorType1:

handler1

except ErrorType2:

handler2

except:

handler0

当Python解释器遇到一个try语句,它会尝试执行try语句体body内的语句,如果没有错误,控制转到try-except后面的语句,如果发生错误,Python解释器会寻找一个符合该错误的异常语句,然后执行处理代码。try-except语句后还能跟else-finally语句。当try中的语句无异常时,执行else中的语句;不管有无异常,总会执行finally中的语句。finally必须在else的后面,不可交换。

def main():
try:
number1,number2=eval(input("Enter two numbers,separated by a comma"))
result=number1/number2
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the put")
except:
print("Somthing wrong in the input")
else:
print("No exceptions,the result is",result)
finally:
print("executing the final clause")
main()


二次方程求解:

import math
def main():
print("This program finds the real solutions to a quadratic\n")
try:
a,b,c=eval(input("Please enter the coefficients(a,b,c):"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root2-(-b-discRoot)/(2*a)
print("\nThe solution are:",root1,root2)
except ValueError:
print("\nNo real roots")
main()


Try…except可以捕捉任何类型的错误 。

对于二次方程,还会有其他可能的错误,如:输入非数值类型 (NameError),输入无效的表达式(SyntaxError) 等。此时可以用一个try语句配多个except来实现。

例如:

import math
def main():
print("This program finds the real solutions to a quadratic\n")
try:
a,b,c=eval(input("Please enter the coefficients(a,b,c):"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root2-(-b-discRoot)/(2*a)
print("\nThe solution are:",root1,root2)
except ValueError as excObj:
if str(excObj)=="math domain error":
print("No Real Roots.")
else:
print("You didn't give me the right number of coefficients.")
except NameError:
print("\nYou didn't enter three numbers.")
except TypeError:
print("\nYour inputs were not all numbers.")
except SyntaxError:
print("\nYour input was not in the correct form.Missing commma?")
except:
print("\nNo real roots")
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异常处理 python