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

參考資料