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.
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
}
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.
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.");
}
}
}
#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
Invalid input! Please enter a valid integer.
Invalid input! Please enter a valid integer.
Complete Code here: GitHub — ssukhpinder/30DayChallenge.Net
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