Day 8 of 30-Day .NET Challenge: Exception Handling
Tags: beginners, programming, csharp, dotnet
Published: 2024-03-27 05:29:23


## 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.
```csharp
    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
```csharp
    #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
```csharp
    /// <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
```csharp
    #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
```

## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)


### 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](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) | [Hashnode](https://dotnet.hashnode.dev/) | [Newsletter](https://www.linkedin.com/newsletters/net-programming-7031098498754195456/) | [Tumblr](https://www.tumblr.com/settings/blog/codewithsukh)

Visit our other platforms: [GitHub](https://github.com/ssukhpinder) | [Instagram](https://www.instagram.com/codewithsukh/) | [Tiktok](https://www.tiktok.com/@codewithsukh) | [Quora](https://www.quora.com/profile/Sukhpinder-Singh-4) | [Daily.dev](https://app.daily.dev/devcard)

More content at [C# Programming](https://medium.com/c-sharp-progarmming)