paint-brush
The 30-Day .NET Challenge - Day 24: How to Avoid Exceptions in Flow Controlby@ssukhpinder
228 reads

The 30-Day .NET Challenge - Day 24: How to Avoid Exceptions in Flow Control

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

Too Long; Didn't Read

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. Exceptions are designed to handle unexpected situations rather than controlling the application flow.
featured image - The 30-Day .NET Challenge - Day 24: How to Avoid Exceptions in Flow Control
Sukhpinder Singh HackerNoon profile picture

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

30 Day .Net Challenge


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.

    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

    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

    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

    #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.




C# Programming🚀

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

Follow us: Youtube | X | LinkedIn | Dev.to Visit our other platforms: GitHub More content at C# Programming