
The try keyword begins an exception handling block. How does try work in the C# programming language? You already know that try is used to implement exception handling, but it is useful to take a deeper look at it.
KeywordsThis C# article introduces the try keyword. Try describes protected regions of code.

Two methods are demonstrated here: the A() method, which uses the try and catch keywords, and the B() method, which does not. In A(), the try denotes that a protected region of code begins. This means when the DivideByZeroException is thrown, the catch block will be entered.
DivideByZeroExceptionProgram that shows try keyword [C#]
using System;
class Program
{
static void Main()
{
A();
B();
}
static void A()
{
try
{
int value = 1 / int.Parse("0");
}
catch
{
Console.WriteLine("A");
}
}
static void B()
{
int value = 1 / int.Parse("0");
Console.WriteLine("B");
}
}
Output
A
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.B() in C:\...\Program.cs:line 25
at Program.Main() in C:\...\Program.cs:line 8
To get a better understanding of what exception handing actually does, let's look at the intermediate representation (IL). When any method uses exception handling (try/catch/finally), the IL shows an ending descriptor (.try ... to ... catch object handler ... to ...). This tells the virtual execution engine how to execute the statements in the method in those ranges.
Intermediate Language Catch Examples FinallyIntermediate representation for A() method [IL]
.method private hidebysig static void A() cil managed
{
.maxstack 2
L_0000: ldc.i4.1
L_0001: ldstr "0"
L_0006: call int32 [mscorlib]System.Int32::Parse(string)
L_000b: div
L_000c: pop
L_000d: leave.s L_001c
L_000f: pop
L_0010: ldstr "A"
L_0015: call void [mscorlib]System.Console::WriteLine(string)
L_001a: leave.s L_001c
L_001c: ret
.try L_0000 to L_000f catch object handler L_000f to L_001c
}Notes. There is no "try" opcode instruction in the same way there is a call instruction. Exception handling is built into the execution engine at all levels. The engine knows as every statement is executed whether it is inside a protected region because of this. Thus, "try" is a keyword that modifies many statements, not an imperative opcode.

We looked at the try keyword in the C# language and tried to understand its implementation. It is used to specify a range of protected statements. This functionality is built into the virtual execution engine at a deep level.
Exception Handling