Python用异常对象来表示异常情况。遇到错误后,会引发异常,如果异常对象未被处理或捕捉,程序就会用所谓的回溯终止信息,
示例:
print 1/0
结果:
Traceback (most recent call last):
File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
print 1/0
ZeroDivisionError: integer division or modulo by zero
raise语句
为了引发异常,可以使用一个类或者实例参数调用raise语句。使用类时,程序会自动创建实例。
示例:
raise Exception
结果:
Traceback (most recent call last):
File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
raise Exception
Exception
捕捉异常
示例:
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except ZeroDivisionError:
print "the second number can't be zero!"
结果:
enter the first number: 3
enter the second number: 0
the second number can't be zero!
用一个块捕捉多个异常
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "your numbers were bogus..."
结果:
enter the first number: 2
enter the second number: 0
your numbers were bogus...
添加else字句
while True:
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
value = x/y
print 'x/y',value
except:
print 'invalid input.please try again.'
else:
break
结果:
enter the first number: 1
enter the second number: 0
invalid input.please try again.
enter the first number: 3
enter the second number: 1
x/y 3
再加上finally语句。
try:
1/0
except ZeroDivisionError:
print "Unknown variable"
else:
print "That went well!"
finally:
print "Cleaning up."
结果:
Unknown variable
Cleaning up.
示例:
print 1/0
结果:
Traceback (most recent call last):
File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
print 1/0
ZeroDivisionError: integer division or modulo by zero
raise语句
为了引发异常,可以使用一个类或者实例参数调用raise语句。使用类时,程序会自动创建实例。
示例:
raise Exception
结果:
Traceback (most recent call last):
File "C:/Users/USER/Desktop/PYluo/test1.py", line 503, in <module>
raise Exception
Exception
捕捉异常
示例:
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except ZeroDivisionError:
print "the second number can't be zero!"
结果:
enter the first number: 3
enter the second number: 0
the second number can't be zero!
用一个块捕捉多个异常
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "your numbers were bogus..."
结果:
enter the first number: 2
enter the second number: 0
your numbers were bogus...
添加else字句
while True:
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
value = x/y
print 'x/y',value
except:
print 'invalid input.please try again.'
else:
break
结果:
enter the first number: 1
enter the second number: 0
invalid input.please try again.
enter the first number: 3
enter the second number: 1
x/y 3
再加上finally语句。
try:
1/0
except ZeroDivisionError:
print "Unknown variable"
else:
print "That went well!"
finally:
print "Cleaning up."
结果:
Unknown variable
Cleaning up.