finally, keyword in C#
The finally block is utilized to execute some specific code which is to be executed whether an exception is thrown or not.so let's see the example below which demonstrates finally, block.
Program
using System;
namespace try_catch_finally
{
class Divide
{
int z;
Divide()
{
z = 0;
}
public void division(int x, int y)
{
try
{
z = x/y;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception Occured {0}", ex);
}
finally
{
Console.WriteLine("Result={0}", z);
}
}
static void Main(string[] args)
{
Divide Div = new Divide();
Div.division(50, 0);
Console.ReadKey();
}
}
}
Output
try_catch.Divide.division(Int32 x, Int32 y)
Result=0
The finally block is utilized to execute some specific code which is to be executed whether an exception is thrown or not.so let's see the example below which demonstrates finally, block.
Program
using System;
namespace try_catch_finally
{
class Divide
{
int z;
Divide()
{
z = 0;
}
public void division(int x, int y)
{
try
{
z = x/y;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception Occured {0}", ex);
}
finally
{
Console.WriteLine("Result={0}", z);
}
}
static void Main(string[] args)
{
Divide Div = new Divide();
Div.division(50, 0);
Console.ReadKey();
}
}
}
Output
try_catch.Divide.division(Int32 x, Int32 y)
Result=0