Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 50 / 68

Cleanup Logic with try/catch/finally

In this lesson you will learn to write cleanup logic with try/catch/finally so certain work always runs whether or not an error occurred. This is for anyone searching for "PHP finally how to use".

A finally block is a cleanup block that always runs, whether an exception was thrown or not. Use it to close files or announce that processing has finished. Cleanup such as closing a file or ending a connection has to happen regardless of errors.

The sample code adds a finally to the try calculation and catch error handling inside divide, always printing "Ending the calculation". Notice how the message appears both in the successful case and in the failing one.

A common stumbling block for beginners is writing a return inside finally. Doing so overwrites the value the try block was going to return, which can lead to behaviour you did not intend.

finally is common wherever you need to release a resource reliably, such as database connections and file handling. Gathering the work needed on both success and failure - closing connections, writing logs - into a finally block prevents duplication.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)