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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
try
{
//here you put code that might cause errors
}
catch (Exception error) //you catch any exception in the variable 'error'
{
//here you can add the code that will run only if you get an error
//note that catching an exception is optional, so you can remove: '(Exception error)'
}
finally
{
//and the code you add in this block will run most of the times (even if you got an error or not)
}
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
try
{
connect_to_server(my_server_address);
//let's say we want to connect to this server that we don't know if it's online or offline
//so we put it into the 'try' block
}
catch(Exception error)
{
//if we got here, the server must be offline (so an exception is thrown)
MessageBox.Show(error.Message); //we show a message if this happens
}
finally
{
MessageBox.Show("Continue running..."); //this message shows up when the try-catch thingy is done
}
|
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:
1
2
3
4
5
6
7
8
9
10
|
try
{
int i = 0;
}
catch(Exception error)
{
i = 1; //'i' doesn't exist here
}
i = 2; //'i' doesn't exist here - but this will throw an exception
|
Sign up here with your email
ConversionConversion EmoticonEmoticon