C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: In the A method, the try keyword denotes that a protected region of code begins.
Note: This means when the DivideByZeroException is thrown, the catch block will be entered.
DivideByZeroExceptionC# program that shows try keyword
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
Here: In this program, no errors occur. It is unlikely that Console.WriteLine will throw an exception here.
And: The try-finally blocks are likely unnecessary. The program shows the try statement's use in the absence of exceptions.
ConsoleC# program that uses try with finally
using System;
class Program
{
static void Main()
{
try
{
Console.WriteLine("A");
}
finally
{
Console.WriteLine("B");
}
}
}
Output
A
B
Note: This tells the virtual execution engine how to execute the statements in the method in those ranges.
Intermediate representation for A: 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
}
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.