异常处理

python使用try…except…可以使程序不因运行错误而崩溃。

try:
    <body>
 except <errortype1>:
      <handler1>
except <errortype2>:
      <handler2>
except:
       <handler0>

例如

while True:
    try:
        x=int(input("please enter a number:"))
        break
    except ValueError:
        print("Oops!That was no valid number.try again...")

输入和输出

please enter a number:kj
Oops!That was no valid number.try again...
please enter a number:ajk
Oops!That was no valid number.try again...
please enter a number:

python异常处理语句还可以使用else和finally关键字。

try:
    <body>
 except <errortype1>:
      <handler1>
except <errortype2>:
      <handler2>
except:
       <handler0>
else:
     <process_else>
finally:
        <process_finally>           

例如

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 input")
    except:
        print("Something wrong in the input")
    else:
        print("No exceptions,the result is",result)
    finally:
        print("executing the final clause")
main()

输入输出

Enter two numbers,separated by a comma:3,4
No exceptions,the result is 0.75
executing the final clause

Enter two numbers,separated by a comma:2,0
Division by zero!
executing the final clause

Enter two numbers,separated by a comma:fhdj
Something wrong in the input
executing the final clause

求二次方根

# quadratic5.py
import math
def main():
    print("This program finds the real solutions to a quadratic\n")
    try:
        a,b,c=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 solutions are:",root1,root2)
    except ValueError:
        print("\nNo real roots")
main()    

输入输出

This program finds the real solutions to a quadratic

Please enter the coefficients (a,b,c):1,2,3

No real roots

try……exceept优点在于它可以用来捕捉任何错误

# quadratic6.py
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)
        root1=(-b-discRoot)/(2*a)
        print("\nThe solutions are:",root1,root2)
    except ValueError as eccObj:
        if str(exObj)=="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 inpt were not all numbers.")
    except SyntaxError:
        print("\nYour input was not the correct form. Missing comma?")
    except:
        print("\nSomething went wrong,sorry!")
main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值