try/catch/finally

This lesson briefs over the usage of try/catch/finally block in C#.

We'll cover the following

Introduction

Catching the problem is a good idea, but it can sometimes leave your program in an invalid state.

For example, if you open a connection to a database, an error occurs and you throw an exception. Where would you close the connection? In both the try AND catch blocks? Well, problems may occur before the close is carried out.

Therefore, the finally statement allows you to cater for the “in all cases do this” circumstance.

Example

See the example below:

Get hands-on with 1200+ tech skills courses.