利用request module呼叫外部服務時透過raise_for_status處理HTTPError, 遇到某一種HTTP code時需要再raise一個自定義的Exception出去, 但發現沒有發揮作用
1 | try: |
先說結論, 因為finally內有return的語法, 所以MyCustomizedException不會被raise, python的官方文件說得很清楚
If the finally clause executes a break, continue or return statement, exceptions are not re-raised.
第二次遇到這種情況, 嘗到沒好好地看文件和紀錄的苦果, 決定記錄下來關於try-except-finally
, return
和 raise
的關係
文件中提到以下注意事項
- If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
- An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.
- If the finally clause executes a break, continue or return statement, exceptions are not re-raised.
- If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.
- If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.
沒有處理或處理過程中又發生其他Exception的時候, 一般來說會在finally block完成後re-raise
在finally block包含break
, continue
或 return
語法時, 不會re-raise
try-except-finally and return
1 | try: |
有三種狀況
- retrun in try
- return in finally
- return in both
1 | # 1. return in try |
1 | # 2. return in finally |
1 | # 3. return in both |
try-except-finally, return and raise
1 | def return_in_try_and_finally_and_no_raise(): |
1 | def return_in_try_with_finally_and_has_raise(): |