Python 用异常对象(exception object)来表示异常情况。
1. 查看内建的异常类:
>>> import exceptions
>>> dir(exceptions)
所有这些异常都可以用在raise语句中:
>>> raise ArithmeticError
2. 创建自己的异常类:
就像其他类一样----只要确保从Exception类继承(不管是间接的或者是直接的,也就是
说继承其他的内建异常类也是可以的)。
例如:
class SomeCustomException(Exception): pass
3. 捕捉异常:
例如:
例如:
4. 捕捉对象:
例如:
5. 真正的全捕捉:
例:
6. 万事大吉:
一些坏事发生时执行一段代码,例:
例:
7. 最后:
Finally子句,用来在可能的异常后进行清理,它和try子句联合使用:
1. 查看内建的异常类:
>>> import exceptions
>>> dir(exceptions)
所有这些异常都可以用在raise语句中:
>>> raise ArithmeticError
2. 创建自己的异常类:
就像其他类一样----只要确保从Exception类继承(不管是间接的或者是直接的,也就是
说继承其他的内建异常类也是可以的)。
例如:
class SomeCustomException(Exception): pass
3. 捕捉异常:
例如:
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!"
except TypeError:
print "That wasn't a number, was it?"
例如:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
except (ZeroDivisionError, TypeError, NameError):
print 'You numbers were bogus...'
4. 捕捉对象:
例如:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError, TypeError), e:
print e
5. 真正的全捕捉:
例:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except:
print 'Something wrong happened...'
6. 万事大吉:
一些坏事发生时执行一段代码,例:
try:
print 'A simple task'
except:
print 'What? Something went wrong?'
else:
print 'Ah... It went as planned.'
例:
while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = x/y
print 'x/y is', value
except:
print 'Invalid input. Please try again.'
else:
break
7. 最后:
Finally子句,用来在可能的异常后进行清理,它和try子句联合使用:
x = None
try:
x = 1/0
finally:
print 'Cleaning up...'
del x