异常
- 异常的种类
ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EnvironmentError EOFError Exception FloatingPointError FutureWarning GeneratorExit ImportError ImportWarning IndentationError IndexError IOError KeyboardInterrupt KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
- 语法结构
try: # 主代码块 pass except KeyError as e: # 异常时,执行该块 pass else: # 主代码块执行完并且无异常,执行该块 pass finally: # 无论异常与否,最终执行该块 pass
- 主动抛出异常
try: raise Exception('错误了。。。') except Exception as e: print(e) #打印:错误了。。。 扩展: e是Exception的对象,print一个对象是先调用了对象的__str__方法,然后把返回的字符串打印
- 自定义异常
class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message try: raise MyException('出错了...') except MyException as e: print(e)
- 断言:如果断言语句为真,代码继续执行,如果为假,则抛出AssertionError异常
assert True print('True') assert False #抛出异常,之后的代码不会执行 print('False')