Python 异常 (8) 持续更新
异常 当程序遇到时,会引发异常。
>>> 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
抛出一个自定义错误
>>> raise Exception("Custom Exception") Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception: Custom Exception
dir 函数列出模块的内容
>>> import exceptions >>> dir(exceptions) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer Error', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'E xception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'I mportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'Key boardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError ', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'R untimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'Unbound LocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'Unicod eTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'Win dowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
自定义异常
# coding=utf-8 # 确定使用新式类 __metaclass__ = type class MyException(Exception): def __init__(self, value): self.value = value try: raise MyException(12) except MyException as e: print 'Exception value:', e.value
输出
Exception value: 12
捕捉异常 try/except
# coding=utf-8 # 确定使用新式类 __metaclass__ = type try: x = input('x:') y = input('y:') print x/y except TypeError: print 'TypeError' except ZeroDivisionError: print 'ZeroDivisionError' try: x = input('x:') y = input('y:') print x/y except (TypeError, ZeroDivisionError), e: print 'Error', e
except (TypeError, ZeroDivisionError), e:
except (TypeError, ZeroDivisionError) as e:
上面两句是一样的。
当没有任何错误时,可以用 try/except/else,看例子
while True: try: x = input('x:') y = input('y:') print x / y except Exception as e: print 'Error', e else: break
finally子句对可能的异常清理
while True: try: x = input('x:') y = input('y:') print x / y except Exception as e: print 'Error', e else: break finally: del x del y

浙公网安备 33010602011771号