Exception Handling abuse
Exceptions are unforseen errors that occur when a program is running. For example, when an application is executing a query, the database connection is lost, Exception is generally used to handle scenarios.
Using exception handling to implement program logical flow is bad and is termed as exception handling abuse.
------------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main()
{
try
{
Console.WriteLine("Please enter Numarator");
int Numarator = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter Denaminator");
int Denaminator = Convert.ToInt32(Console.ReadLine());
int Result = Numarator / Denaminator;
Console.WriteLine("Result = {0}", Result);
Console.ReadLine();
}
catch(FormatException)
{
Console.WriteLine("Please enter valid number ");
Console.ReadLine();
}
catch(OverflowException)
{
Console.WriteLine("Only numbers beteen {0} && {1}", Int32.MinValue, Int32.MaxValue);
Console.ReadLine();
}
catch(DivideByZeroException)
{
Console.WriteLine("Denominator cannot be Zero");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
=======================================================================
EXCEPTION HANDLING ABUSE RESOLVED..
CORRECT WAY TO USE EXCEPTION HANDLING AFTER VALIDATION
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main()
{
try
{
Console.WriteLine("Please enter Numarator");
int Numarator;
bool IsNumaratorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Numarator);
if (IsNumaratorConversionSuccessful)
{
Console.WriteLine("Please enter Denominator");
int Denominator;
bool IsDenominatorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Denominator);
if (IsDenominatorConversionSuccessful && Denominator != 0)
{
int Result = Numarator / Denominator;
Console.WriteLine("Result = {0}", Result);
Console.ReadLine();
}
else
{
if (Denominator == 0)
{
Console.WriteLine("Denominator cannot be Zero");
Console.ReadLine();
}
else
{
Console.WriteLine("Denominator should be valid number between {0} && {1}", Int32.MinValue, Int32.MaxValue);
Console.ReadLine();
}
}
}
else
{
Console.WriteLine("Numarator should be valid number between {0} && {1}", Int32.MinValue, Int32.MaxValue);
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
Too Good Man.
ReplyDelete