Python异常处理
Python 用异常对象(exception object)来表示异常情况。
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/yexcept 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...'
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/yexcept (ZeroDivisionError, TypeError), e: print e
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/yexcept: print 'Something wrong happened...'
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
x = None try: x = 1/0 finally: print 'Cleaning up...' del x