C# Try-Catch-Finally Tutorial

1.Short intro:

Try-Catch-Finally is a nice way to handle any encountered exceptions without crashing your program. This means your program will still run even if you got an ‘unexpected’ error.

2.How to use?

It’s simple! As the name says, you have 3 blocks available to use: try, catch and finally.
In C#, this is how you use them:


3.When to use this? + Example

You should use it when you really can’t validate the data or when you expect exceptions from your code.
A short example of when to use this:
Let’s say you want your application to communicate with a server – that server might be offline, and if this happens your program will show an error and will stop executing. We don’t want this to happen, because this denotes lack of professionalism, so we must show a nice error (telling the user what’s going on).

Here’s a short code that solves the problem above:

4.Additional info

One thing to note is that variables declared inside of try, catch or finally can’t be used outside of the block:
That’s all you might want to know about how to use try-catch-finally. Try using those blocks in simple applications and once you understand how they work, everything will become clearer.
Previous
Next Post »