Python异常处理

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值