Day 24 of 30-Day .NET Challenge: Avoid Exceptions in Flow Control
Tags: csharp, dotnet, beginners, programming
Published: 2024-04-14 06:12:00

Learn to enhance your C# code’s performance and readability by avoiding exceptions for flow control. Discover a better approach using TryParse on Day 24 of our 30-Day .NET Challenge.


## Introduction

Exceptions are designed to handle unexpected situations rather than controlling the application flow. Using exceptions during input validation can affect your application's readability and performance.

### Learning Objectives

* The inefficient use of exceptions

* A better approach using TryParse

### Prerequisites for Developers

* Basic understanding of C# programming language.

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

### The inefficient use of exceptions

Using exceptions for flow control, especially in a loop or frequently called code, may lead to severe performance bottlenecks. It also makes code hard to understand.

Exceptions are really expensive in terms of system resources because when an exception is triggered, .Net runtime captures the stack trace and the process is resource-intensive.
```csharp
    try
    {
        int.Parse(input); // Attempt to parse input
    }
    catch (FormatException)
    {
        // Handle the invalid input
    }
```
### A better approach using TryParse

Please find below the refactored version of the previous code snippet
```csharp
    if (int.TryParse(input, out int result))
    {
        // Use the parsed value
    }
    else
    {
        // Handle the invalid input
    }
```
The aforementioned code attempts to parse the input supplied from the console and returns a boolean whether it's a success or failure.

## Complete Code

Create another class named AvoidExceptions and add the following code snippet
```csharp
    public static class AvoidExceptions
    {
        public static void BadWay(string input)
        {
            // Inefficient way: Using exceptions for flow control
            try
            {
                int number = int.Parse(input);
                Console.WriteLine($"You entered (Exception method): {number}");
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid input! Please enter a valid integer.");
            }
        }
    
        public static void GoodWay(string input)
        {
            // Efficient way: Using TryParse for flow control
            if (int.TryParse(input, out int result))
            {
                Console.WriteLine($"You entered (TryParse method): {result}");
            }
            else
            {
                Console.WriteLine("Invalid input! Please enter a valid integer.");
            }
        }
    }
```
## Execute from the main method as follows
```csharp
    #region Day 24: Avoid Exceptions in Flow Control
    static string ExecuteDay24()
    {
        Console.WriteLine("Enter a number:");
    
        string input = Console.ReadLine();
        AvoidExceptions.BadWay(input);
        AvoidExceptions.GoodWay(input);
        return "Executed Day 24 successfully..!!";
    }
    
    #endregion
```
## Console Output
```
    Invalid input! Please enter a valid integer.
    Invalid input! Please enter a valid integer.
```
## 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:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)