paint-brush
The 30-Day .NET Challenge, Day 8: Exception Handlingby@ssukhpinder

The 30-Day .NET Challenge, Day 8: Exception Handling

by Sukhpinder SinghMarch 27th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. Examine the basic categories of exceptions and review some common system exceptions.
featured image - The 30-Day .NET Challenge, Day 8: Exception Handling
Sukhpinder Singh HackerNoon profile picture

Introduction

Throughout this module, you will gain knowledge about exceptions, the process of handling exceptions, and the different exception-handling patterns that C# supports.

Learning Objectives:

  • Examine the basic categories of exceptions and review some common system exceptions.

Prerequisites for Developers

  • Visual Studio Code configured for C# application development
  • Ability to create C# console applications with iteration, selection, and custom methods for business logic
  • Understanding of error handling and exceptions in C#
  • Experience using Visual Studio Code debugging tools for C#

Getting Started

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

Console Output

    Hello from try block
    Hello from exception block
    Hello from finally block

Nested Exception Handling

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:

  1. The program starts executing within the code block of the outer try statement.
  2. An exception is triggered within the code block of the inner try statement.
  3. The runtime identifies the catch clause linked to the outer try statement.
  4. Before transferring control to the initial line of the catch code block, the runtime executes the final clause tied to the inner try statement.
  5. Subsequently, control shifts to the beginning of the catch code block, where the code for handling the exception is executed.

Execute the code from the main method as follows

    #region Day 8 - Exception Handling
    
    ExceptionHandling.NestedExceptionBlock();
    
    #endregion

Console Output

    Hello from try block
    Hello from inner finally block
    Hello from exception block
    Hello from outer finally block

C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

If you’ve made it this far, please show your appreciation with a clap and follow the author! 👏️️

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.