标签:traceback shel try error module shell error: put ace
演示一个程序异常
>>> anumber = int(input("Please enter an integer "))
Please enter an integer -23
>>> print(math.sqrt(anumber))
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
print(math.sqrt(anumber))
ValueError: math domain error
>>>
利用try处理异常,让程序不会因为异常而终止
>>> try:
print(math.sqrt(anumber))
except:
print("Bad Value for square root")
print("Using absolute value instead")
print(math.sqrt(abs(anumber)))
Bad Value for square root
Using absolute value instead
4.79583152331
>>>
使用 raise 语句,来提前提示异常,并且终止程序
>>> if anumber < 0:
... raise RuntimeError("You can‘t use a negative number")
... else:
... print(math.sqrt(anumber))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
RuntimeError: You can‘t use a negative number
>>>
标签:traceback shel try error module shell error: put ace
原文地址:https://www.cnblogs.com/mk123/p/11507390.html