Exception 例外处理

Python 基础: Exception 例外处理

try except 例外处理执行顺序

顺序 例外处理 说明
1 try 尝试执行 try 中的 code
2 except 例外类别处理
3 else 没有发生例外执行的程式
4 finally try 跑完后一定会执行的程式

取得 Exception 例外

try:
    raise Exception('custom error', 333)
except Exception as e:
    print('1. Exception: ', e)
    print('1. Exception argument: ', e.args)
else:
    print('2. else process')
finally:
    print('3. finally process')


# 1. Exception:  ('custom error', 333)
# 1. Exception argument:  ('custom error', 333)
# 3. finally process

try 执行正常没有丢出例外

try:
    print('0. process code')
except Exception as e:
    print('1. Exception: ', e)
    print('1. Exception argument: ', e.args)
else:
    print('2. else process')
finally:
    print('3. finally process')

# 0. process code
# 2. else process
# 3. finally process

自定义 Exception

class CustomException(Exception):
    """Raised when the input value is too small"""
    pass


try:
    raise CustomException('custom error', 333)
except CustomException as e:
    print('1.1 CustomException: ', e)
    print('1.1 CustomException argument: ', e.args)
except Exception as e:
    print('1. Exception: ', e)
    print('1. Exception argument: ', e.args)
else:
    print('2. else process')
finally:
    print('3. finally process')

# 1.1 CustomException:  ('custom error', 333)
# 1.1 CustomException argument:  ('custom error', 333)
# 3. finally process

参考资料