try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise
>>> defthis_fails(): x = 1/0 >>> try: this_fails() except ZeroDivisionError as err: print('Handling run-time error:', err) Handling run-time error: int division or modulo by zero
try-finally 语句
try-finally 语句无论是否发生异常都将执行最后的代码。
以下实例中 finally 语句无论异常是否发生都会执行:
实例
1 2 3 4 5 6 7 8 9 10 11 12
try: runoob() except AssertionError as error: print(error) else: try: withopen('file.log') as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) finally: print('这句话,无论异常是否发生都会执行。')
抛出异常
Python 使用 raise 语句抛出一个指定的异常。
raise语法格式如下:
1
raise [Exception [, args [, traceback]]]
以下实例如果 x 大于 5 就触发异常:
1 2 3
x = 10 if x > 5: raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
执行以上代码会触发异常:
1 2 3 4
Traceback (most recent call last): File "test.py", line 3, in <module> raise Exception('x 不能大于 5。x 的值为: {}'.format(x)) Exception: x 不能大于 5。x 的值为: 10
classError(Exception): """Base class for exceptions in this module.""" pass
classInputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """
classTransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """