Try. The try keyword begins an exception handling block. Control flow enters a protected region. If an error occurs in a statement in a try block, another path may be reached.
We already know that try is used to implement exception handling, but it is useful to take a closer look. Try is implemented with a special instruction in the intermediate language.
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");
}
}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
Finally. The try keyword is not only used to deal with potential errors. It is also used with finally. A finally block executes always after the completion of the try block statements.
using System;
class Program
{
static void Main()
{
try
{
Console.WriteLine("A");
}
finally
{
Console.WriteLine("B");
}
}
}A
B
Protected regions. We next look at the intermediate representation (IL). When a method uses exception handling, the IL shows an ending descriptor (try, to, catch object handler, to).
Note This tells the virtual execution engine how to execute the statements in the method in those ranges.
.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, opcodes. 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.
And The engine knows at every statement whether it is inside a protected region.
Thus Try is a keyword that modifies many statements, not an imperative opcode.
Summary. We used the try keyword. And we tried to understand its implementation. It specifies a range of protected statements, and is always used with catch or finally.
This functionality is built into the virtual execution engine at a deep level. Try is an important and useful C# keyword. It helps with the development of error-proof, reliable code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).