When and why can `finally` be useful?

后端 未结 2 971
不思量自难忘°
不思量自难忘° 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:02

    You might not catch the exception you're throwing, but you still want to run your finally statement before throwing an error (eg. always close a log file or a DB connection before fatally failing because you didn't catch the exception):

    getMessage();
        fwrite($fHandle, 'Threw a RangeException: ' . $e->getMessage());
    } finally {
        // Always make sure that we close the file before throwing an exception, even if we don't catch it
    
        echo 'Reached the finally block';
        fwrite($fHandle, 'Reached the finally block');
        fclose($fHandle);
    }
    

    Which would output:

    Throwing exception..Reached the finally block
    Fatal error: Uncaught exception 'BadFunctionCallException' in /tmp/execpad-dc59233db2b0/source-dc59233db2b0:6
    Stack trace:
        #0 {main}
        thrown in /tmp/execpad-dc59233db2b0/source-dc59233db2b0 on line 6
    

    DEMO (without the fopen as eval.in doesn't support it)

提交回复
热议问题