Exception in C#

By   Calendar icon Jan 10, 2020   Level 1 icon

Description:

Here we explain what an exception is and how to deal with the exceptions. We also give some examples of use.

Preferencesoft

During the execution of a program, when an instruction is not able to give you a result under certain conditions, it can throw an exception, which will result in exiting the program part in which it was located and going to an exception treatment subprogram or block.

Some exceptions (e.g. misreading or writing in a file) are managed by basic instructions or instructions of some libraries but can be retrieved with try catch finally.

The finally try catch composed statement allows you to execute the try block instructions and jump immediately at the beginning of the catch block in the event of an exception being raised, the finally block being used to execute instructions in any case whether there was an exception or not.

Structure of a C# exception

When an exception is launched, the current flow of the code is interrupted and jumps directly at the beginning of the catch block corresponding to the exception caused and then continues its way into that block and resumes in the main block containing the statement try, catch finally.

Instruction try catch finally

  • try is followed by a block of instructions, some of which can trigger an exception.
  • catch is followed by a block of instructions that deal with a particular exception.
    There may be several catch keywords attached to different exceptions.
  • finally is followed by a statement block that run in all cases whether an exception is triggered or not.
  • throw can throw an exception from anywhere in a program

try 
{
   // statements that can trigger an exception
}
catch (<ExceptionClassName> <except> )
{
   // statements handling the exception
}
finally
{
   // statements
}

try 
{
   // statements that can trigger an exception
}
catch( <ExceptionClassName1> <e1> )
{
   // error handling statements
} 
catch( <ExceptionClassName2> <e2> )
{
   // error handling statements
}
catch( <ExceptionClassNameN> <eN> )
{
   // error handling statements
}
finally
{
   // statements 
}

System exception

Let's give an example in which we deliberately cause an error by overstepping the bounds of the array.
This has the effect of getting out of an infinite loop. Here we use goto instruction for the infinite loop.
But it is not advisable to cause an error to get out of a loop.
Example 1

using System;

public class Program
{

    public static void Main()
    {
        int i = 0;
        int[] arr = new int[] { 1, 5, 6, 8, 9 };
        try
        {
        start:
            arr[i++] *= 2;
            goto start;
        }
        catch { }
        Console.WriteLine("{0}", arr[1]);
    }
}

Example 2

using System;

public class Program
{
    public static void Main(string[] args)
    {
        int a = 1;
        try
        {
            a = 1 / (a - 1);
            Console.WriteLine("a={0}", a);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("a-1 is equal to 0");
        }
    }
}

User defined exception

It is possible to define our own exceptions. To create a user defined exception, simply create a class derived from the exception class.

Now let's write a program that declares a custom exception, which can be lifted when a person is not employed in a company.

using System;
public class InvalidEmployeeException : Exception
{
    public InvalidEmployeeException(String message) : base(message)
    {

    }
}
public class TestEmployeeException
{
    static string[] employeeList = { "Bill Halliday", "Kate MacDo" };
    static void CheckEmployee(string name)
    {
        if (Array.IndexOf(employeeList, name) < 0)
        {
            throw new InvalidEmployeeException(string.Format("{0} is not an employee of the company", name));
        }
    }
    public static void Main(string[] args)
    {
        try
        {
            CheckEmployee("Bill Halliday");
            CheckEmployee("Jimmy Connors");
        }
        catch (InvalidEmployeeException e)
        {
            Console.WriteLine(e);
        }
    }
}

InvalidEmployeeException: Jimmy Connors is not an employee of the company at TestEmployeeException.CheckEmployee(String name) in d:\Windows\Temp\wtyydrw0.0.cs:line 16 at TestEmployeeException.Main(String[] args) in d:\Windows\Temp\wtyydrw0.0.cs:line 24

CSharp

Categories