Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 50 / 68

Cleaning up with Try / Catch / Finally

This lesson covers cleanup with VB.NET's Try / Catch / Finally, with the aim of running something whether or not an error occurred.

A Finally block is where work goes that must run whether or not an error occurred — closing a file, dropping a connection, anything that needs tidying up.

In the sample code, Divide() catches a division-by-zero error with Catch and always shows "Ending the calculation" from the Finally block. Note the Integer? return type, which lets it also return Nothing when there is no value.

A common early stumble is when Finally runs. Even if the Try block returns, Finally runs first — miss that ordering and the flow is easy to misread.

In professional work, Finally is used wherever an external resource such as a file or a database connection has been opened and must reliably be closed, however things end.

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

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