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