try:
#被检测的程序
except xError: # 有异常执行except
# x这种错误
except yError:
# y这种错误
except: # except子句可以省略异常名,以用作通配符,即所有错误
# 何种错误
else: # 没有异常则执行else
print("没有错误,结果为")
finally: # 有异常或无异常,都会执行finally finally常用来释放 try语句块中申请的资源
#下面的程序操作
有异常执行except,无异常执行else,finally最终都会执行
else和finally都可没有
例子:
1.检测一元二次方程异常简易版:
# quadratic5.py
import math
def main():
try:
a,b,c=eval(input("请输入三个数,并用逗号隔开"))
delta=math.sqrt(b*b-4*a*c)
root1=(-b+delta)/(2*a)
root2=(-b-delta)/(2*a)
print("结果为{},{}".format(root1,root2))
except ValueError:
print("无实根")
main()
2.检测两个数相除可能出现的异常:
#TryException.py
def main():
try:
number1,number2=eval(input("请输入两个数,并用逗号隔开"))
result=number1/number2
except ZeroDivisionError:
print("不能除0")
except SyntaxError:
print("语法错误")
except:
print("输入或输出有些什么错误")
else:
print("没有错误,结果为{}".format(result))
finally:
print("执行下面的程序")
main()
3.1.检测一元二次方程异常困难版:
# quadratic5.py
import math
def main():
try:
a,b,c=eval(input("Please enter the coefficients(a,b,c):"))
delta=math.sqrt(b*b-4*a*c)
root1=(-b+delta)/(2*a)
root2=(-b-delta)/(2*a)
print("\nThe solutions are:{},{}".format(root1,root2))
except ValueError as excObj:
if(str(excObj)=="math domain error"):
print("\nNo real roots")
else:
print("\nYou 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 comma")
except:
print("\nSomething went wrong,sorry!")
main()