2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHP try catchのcatch内部でreturnしてもfinallyの処理は必ず実行されるらしい

Last updated at Posted at 2024-03-14

概要

try catch finallyにてcatch内部でreturnを行っても、必ずfinallyは実行されるらしいことを恥ずかしながら初めて知ったので簡単にまとめる。

内容

PHPの公式ドキュメントには下記のように書かれている

return 文が try や catch ブロックの内部に存在した場合でも、 finally ブロックは実行されます。

catchで例外を再度スローしてもfinallyが実行されることは知っていたが、returnでもfinallyが実行されることは知らなかった。

例えば下記のような処理があったとして、例外をキャッチしたとする。当該の例外がHogeExceptionだった場合、エラーメッセージがreturnされている。このとき一見catchの中でreturnしているので処理は終わりかと思うが、finallyがある場合、必ず実行されるらしい。

try {
    // DBへの書き込み処理などなど
} catch (Exception $e) {

    if ($e instanceof HogeException) {
        return $e->getMessage();
    }
    
    throw $e;
} finally {
    // クリーンアップなどの後始末処理
}

参考文献

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?