Exceptions and Defensive Coding
Finally Clause
A finally block runs after the try/catch path finishes.
Finally Clause
FinallyClause.cs
using System;
class Program
{
static void Main()
{
string mode = ;
bool closed = false;
string status = "started";
try
{
if (mode == "fail")
{
throw new InvalidOperationException("demo");
}
status = "finished";
}
catch (InvalidOperationException)
{
status = "handled";
}
finally
{
closed = true;
}
Console.WriteLine($"mode={mode}");
Console.WriteLine($"status={status}");
Console.WriteLine($"closed={closed}");
}
}
using System;
class Program
{
static void Main()
{
string mode = ;
bool closed = false;
string status = "started";
try
{
if (mode == "fail")
{
throw new InvalidOperationException("demo");
}
status = "finished";
}
catch (InvalidOperationException)
{
status = "handled";
}
finally
{
closed = true;
}
Console.WriteLine($"mode={mode}");
Console.WriteLine($"status={status}");
Console.WriteLine($"closed={closed}");
}
}
using System;
class Program
{
static void Main()
{
string mode = ;
bool closed = false;
string status = "started";
try
{
if (mode == "fail")
{
throw new InvalidOperationException("demo");
}
status = "finished";
}
catch (InvalidOperationException)
{
status = "handled";
}
finally
{
closed = true;
}
Console.WriteLine($"mode={mode}");
Console.WriteLine($"status={status}");
Console.WriteLine($"closed={closed}");
}
}
finally
A `finally` block runs for both successful and handled failing paths.