C# try-catch-finally
In C#, try, catch and finally keywords are used to handle exceptions. An exception is an error that occurs during the execution of the program.
Use of try, catch and finally
try – The try block contains the statements that might create an exception. It is followed by one or more catch blocks.
catch – The catch block handles the exceptions thrown from try block.
finally – Code specified in finally block is always executed. It can be used to release resources used in the try block. For example, closing any database connections or files opened in the try block.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnCSharp
{
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 0;
int c;
try
{
c = a / b;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
a = b = c = 0;
Console.WriteLine("In finally block.");
//You can close any database connections or opened file streams here.
}
Console.WriteLine("The value of c is {0}", c);
Console.ReadKey();
}
}
}
Output
Attempted to divide by zero.
In finally block.
The value of c is 0