Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 43 - C# Tutorial - Exception Handling abuse

Exceptions are unforeseen errors that occur when a program is running. For example, when an application is executing a query, the database connection is lost. Exception handling is generally used to handle these scenarios. 


But many a times I have seen programmers using exception handling to implement programming logic which is bad, and this is called as exception handling abuse.

Part 43 - C# Tutorial - Exception Handling abuse



Program using exception handling to implement logical flow:
using System;
public class ExceptionHandlingAbuse
{
    public static void Main()
    {
        try
        {
            Console.WriteLine("Please enter Numerator");
            int Numerator = Convert.ToInt32(Console.ReadLine());


            Console.WriteLine("Please enter Denominator");
            //Convert.ToInt32() can throw FormatException, if the entered value
            //cannot be converted to integer. So use int.TryParse() instead
            int Denominator = Convert.ToInt32(Console.ReadLine());


            int Result = Numerator / Denominator;


            Console.WriteLine("Result = {0}", Result);
        }
        catch (FormatException)
        {
            Console.WriteLine("Only numbers are allowed!");
        }
        catch (OverflowException)
        {
            Console.WriteLine("Only numbers between {0} & {1} are allowed",
                Int32.MinValue, Int32.MaxValue);


        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Denominator cannot be zero");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
In Part 44, we will learn how to prevent exception handling abuse. please click here to watch it now.

1 comment:

  1. Hello Venkat,
    In this video you explained how exception handling can be abused, but here it has not become clear to me *why* such use is considered abuse or bad practice.
    In contrary, the example code you introduced looks more clear than other approaches with tryParse etc., since the kind of errors that might occur are cleary visible on the very first sight (highlighted exception names in Visual Studio) and so are the actions taken in each case.
    I guess however, that exceptions are somewhat expensive concerning performance, and that might be the reason why such use is considered bad, right?

    Don P

    ReplyDelete

It would be great if you can help share these free resources