Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 50 / 68

Cleanup Logic with try/catch/finally

In this lesson you will learn how to write cleanup logic with try/catch/finally in C#, so certain work always runs whether or not an error occurred. This is for anyone searching for "C# try catch 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.

The sample code catches a divide-by-zero error inside Divide() with catch, and always prints "Ending the calculation" from the finally block regardless of whether anything failed. Notice the int? return type, which also allows returning null when there is no value.

A common stumbling block for beginners is when finally actually runs. Be careful: a return inside finally overwrites the value the try block was going to return.

In real-world development, a using statement gives you an even more concise option that releases resources automatically without writing a finally block at all.

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

๐Ÿงช This site can't compile or run C# 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)