Exception handling in C#

In every program, sometimes there is a mistake with C #, we bless with a good compiler, obviously it can not see every mistake, and in those cases, the .NET framework will throw exceptions, we will To tell that something went wrong. In the first chapter, about the arrays, I describe how to get an exception. Let's get the example:


using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[2];

            numbers[0] = 23;
            numbers[1] = 32;
            numbers[2] = 42;

            foreach(int i in numbers)
                Console.WriteLine(i);
            Console.ReadLine();
        }
    }
}

Okay, try to run this example, and you will see what I'm talking about. Do you see what we are doing wrong? We have defined an array of integers with 2 objects for the room, yet we try to use 3 places in it, of course, it leads to an error, you will see if you can try . When the scene is run in C # Express, IDE gives us some options for the exception, but if you double-click the EXE file and try to execute the program, you will get a dirty error. If you know that there may be an error, you should handle it. This is where exceptions are used. Here is a slightly modified version of the code from above:


int[] numbers = new int[2];
try
{
    numbers[0] = 23;
    numbers[1] = 32;
    numbers[2] = 42;

    foreach(int i in numbers)
        Console.WriteLine(i);
}
catch
{
    Console.WriteLine("Something went wrong!");
}
Console.ReadLine();

If it comes to handling this error, then I present to you my new best friend: Try ..catch. Block Block Now try to run the program, and see the difference - instead of Visual C # Express / Windows Let us know that there has been a serious problem, we start telling our story, but will it not be good if we can tell what went wrong? no problem:


catch(Exception ex)
{
    Console.WriteLine("An error occured: " + ex.Message);
}

As you can see, we have added something to the catch statement. Now we show that with the exception we want to catch the basis of all the exceptions of this exception, we get some information about the problem. By making exceptions, and by outputting message assets, we get a sound description of the problem.

As I said, exception is the most common type of exception. The rules of handling exceptions tell us that we should always use the usual type of exception, and in this case, we actually know that what is the exact type of exceptions generated by our code? Because the visual studio told us how we did not manage it. If you are in doubt, then the documentation usually tells you how the method can throw a method (methods) The second way of knowing the exception tells us to use the class - change it to the output line:


Console.WriteLine("An error occured: " + ex.GetType().ToString());

The result, as expected, IndexOutRangeException should handle this exception, but anything prevents us from dealing with many exceptions. In some situations, you may want to talk differently, depending on which exception was thrown. Just change our catch block to:


catch(IndexOutOfRangeException ex)
{
    Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
    Console.WriteLine("Some sort of error occured: " + ex.Message);
}

As you can see, we first look for indexation orders, if we do it in another way, the catch block will be obtained with the exception class, because it is removed from all the exceptions. So in other words, you should first use the most specific exceptions.

You should know about exceptions that ultimately block blocks can be finally added to the set of blocks or can be used exclusively based on your needs. The code inside the block is not always an exception or exception. This is a good place if you have to close the file context or arrange the object that you no longer need. Since our examples were very simple, since the garbage collector handles it, we do not really need cleaning. But since you ultimately need a hurdle, there is the possibility of running under those circumstances, here is an extended version of our example:

int[] numbers = new int[2];
try
{
    numbers[0] = 23;
    numbers[1] = 32;
    numbers[2] = 42;

    foreach(int i in numbers)
        Console.WriteLine(i);
}
catch(IndexOutOfRangeException ex)
{
    Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
    Console.WriteLine("Some sort of error occured: " + ex.Message);
}
finally
{
    Console.WriteLine("It's the end of our try block. Time to clean up!");
}
Console.ReadLine();

If you run the code, you will see that the first exception block and finally the block is executed. If you delete the line that adds the number 42 to the array, you will see that the block has reached the end.

Knowing about exceptions is an important part, this is the way how exceptions arise. All unrestricted exceptions are not fatal for your application, but when they are not, you should not expect to execute the remaining code. On the other hand, if you handle the exception, then lines will be executed only after the attempt line. In our example, the loop, which outputs the values ​​of the array, never reaches, because after the exception is thrown, the attempted block eventually goes to the block (s), however, the last line, where we Reads to stop the application from the console immediately coming out, reaches. You should always keep this in mind while trying the blocks.