Throughout this module, you will gain knowledge about exceptions, the process of handling exceptions, and the different exception-handling patterns that C# supports.
In C#, exception handling is achieved through the utilization of the try, catch, and finally keywords. Each of these keywords is linked with a distinct code block and serves a particular purpose in managing exceptions.
To begin, create a static class file called “ExceptionHandling.cs” within the console application. Insert the provided code snippet into this file.
public static class ExceptionHandling
{
/// <summary>
/// Outputs
/// Hello from try block
/// Hello from exception block
/// Hello from finally block
/// </summary>
public static void SimpleExceptionBlock()
{
try
{
// try code block - code that may generate an exception
Console.WriteLine("Hello from try block");
throw new NotImplementedException();
}
catch
{
// catch code block - code to handle an exception
Console.WriteLine("Hello from exception block");
}
finally
{
// finally code block - code to clean up resources
Console.WriteLine("Hello from finally block");
}
}
}
Execute the code from the main method as follows
#region Day 8 - Exception Handling
ExceptionHandling.SimpleExceptionBlock();
#endregion
Hello from try block
Hello from exception block
Hello from finally block
Add another method into the same static class as shown below
/// <summary>
/// Outputs
/// Hello from try block
/// Hello from inner finally block
/// Hello from exception block
/// Hello from outer finally block
/// </summary>
public static void NestedExceptionBlock()
{
try
{
// Step 1: code execution begins
try
{
// Step 2: an exception occurs here
Console.WriteLine("Hello from try block");
throw new NotImplementedException();
}
finally
{
// Step 4: the system executes the finally code block associated with the try statement where the exception occurred
Console.WriteLine("Hello from inner finally block");
}
}
catch // Step 3: the system finds a catch clause that can handle the exception
{
// Step 5: the system transfers control to the first line of the catch code block
Console.WriteLine("Hello from exception block");
}
finally
{
Console.WriteLine("Hello from outer finally block");
}
}
In this scenario, the following sequence of events unfolds:
Execute the code from the main method as follows
#region Day 8 - Exception Handling
ExceptionHandling.NestedExceptionBlock();
#endregion
Hello from try block
Hello from inner finally block
Hello from exception block
Hello from outer finally block
Thank you for being a part of the C# community! Before you leave:
Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr
Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev
More content at C# Programming
Also published here.