When and why can `finally` be useful?

后端 未结 2 950
不思量自难忘°
不思量自难忘° 2021-01-18 03:33

PHP 5.5 has implemented finally to try-catch. My doubt is: when exactly try-catch-finally that might be more helpful than just I write

2条回答
  •  情歌与酒
    2021-01-18 04:00

    The code within the finally block is always executed after leaving from either try or catch blocks. Of course you may continue writing code after the try-catch and it will be executed as well. But finally could be useful when you'd like to break out of code execution (such as returning from a function, breaking out of a loop etc.). You can find some examples on this page - http://us2.php.net/exceptions, such as:

    function example() {
      try {
         // open sql connection
         // Do regular work
         // Some error may happen here, raise exception
      }
      catch (Exception $e){
        return 0;
        // But still close sql connection
      }
      finally {
        //close the sql connection
        //this will be executed even if you return early in catch!
      }
    }
    

    But yes, you are right; finally is not very popular in everyday use. Certainly not as much as try-catch alone.

提交回复
热议问题