Today we are going to speak about exception handling, operator overloading and Extension Methods.

Agenda

Exception handling

The C# language’s exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. Exceptions are created by using the throw keyword.

How try-catch operator looks:

try
{
    //ToDo: your code goes here
}
catch
{
    //ToDo: if something goes wrong,
    //ToDo: this block of code will be executed
}

try-catch operator in action demo:

while (true)
{
    Console.WriteLine("Calculation started.");
    try
    {
        Console.Write("Enter a: ");
        int a = int.Parse(Console.ReadLine());
        Console.Write("Enter b: ");
        int b = int.Parse(Console.ReadLine());
        Console.WriteLine($"{a}/{b} = {a/b}");
    }
    catch
    {
        Console.WriteLine("Operation failed.");
    }

    Console.WriteLine("Would you like continue calculations? y/n");
    if (Console.ReadLine().ToLower() != "y")
    {
        break;
    }
}
Console.WriteLine("Good bye!");

try-catch-finally operator in action demo:

while (true)
{
    Console.WriteLine("Calculation started.");
    try
    {
        Console.Write("Enter a: ");
        int a = int.Parse(Console.ReadLine());
        Console.Write("Enter b: ");
        int b = int.Parse(Console.ReadLine());
        Console.WriteLine($"{a}/{b} = {a/b}");
    }
    catch (Exception e)
    {
        Console.WriteLine("Operation failed. Message: {0}", e);
    }
    finally
    {
        Console.WriteLine("Current calculation completed.");
    }

    Console.WriteLine("Would you like continue calculations? y/n");
    if (Console.ReadLine().ToLower() != "y")
    {
        break;
    }
}

try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it. finally block will be always executed despite exception occured or not.

Let’s create a custom exception class. In order to create an exception handling class, it has to be inherited from System.Exception type, like shown on demo below:

class AttendanceException : Exception
{
    public AttendanceException()
    {
    }

    public AttendanceException(string message) : base(message)
    {
    }

    public AttendanceException(string message, Exception innerException) : base(message, innerException)
    {
    }

    protected AttendanceException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}

Application that uses this class can be similar to:

int pupilsNumber = 0;
try
{
    pupilsNumber = int.Parse(Console.ReadLine());

    if (pupilsNumber == 0)
    {
        throw new AttendanceException("Everybody absent");
    }
}
catch (AttendanceException)
{
    Console.WriteLine("Lesson is ignored :(");
}
catch (Exception e)
{
    Console.WriteLine(e);
}

Console.WriteLine($"{pupilsNumber} pupils here");

Please pay your attention to throw operator. The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

Operator overloading

C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Not all operators can be overloaded, however, and others have restrictions, as listed by this link

Example of overloaded operator:

class Material
{
    public int Weight { get; set; }
    public string Name { get; set; }

    public static Material operator + (Material m1, Material m2)
    {
        return new Material
        {
            Name = m1.Name+" and "+ m2.Name,
            Weight = m1.Weight + m2.Weight
        };
    }
}

And its usage:

Material water = new Material
{
    Name = "Water",
    Weight = 120
};

Material salt = new Material
{
    Name = "Salt",
    Weight = 15
};

Material solterWater = water + salt;

Console.WriteLine($"{solterWater.Name}, {solterWater.Weight}");

Extension Methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Example below demonstrates how to add additional functionality for int type.

public static class IntExtensions
{
    public static int Increment(this int n, int amount)
    {
        return n + amount;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(10.Increment(3));
        Console.ReadLine();
    }
}

References

Presentation

Lesson 10 from Alex Honcharuk