articles

Home / DeveloperSection / Articles / Example of Exception handling in C#

Example of Exception handling in C#

Anonymous User4293 21-May-2015

Hi everyone in this article I’m explaining about exception handling in c# .net.

Details:

In every program, things go wrong sometimes. With C#, we're blessed with a good compiler, which will help us prevent some of the most common mistakes. Obviously it can't see every error that might happen, and in those cases, the .NET framework will throw an exception, to tell us that something went wrong. Let's bring the example:

Syntax:

staticvoid Main(string[] args)
{
     int[] numbers = newint[2];
 
     numbers[0] = 23;
     numbers[1] = 32;
     numbers[2] = 42;
 
     foreach (int i in numbers)
         Console.WriteLine(i);
     Console.ReadLine();
}

 

Okay, try running this example, and you will see what I'm talking about. Do you see what we're doing wrong? We have defined an array of integers with room for 2 items, yet we try to use 3 spaces in it. Obviously, this leads to an error, which you will see if you try to run this example. When run inside Visual C# Express, the IDE gives us some options for the exception, but if you try to execute the program by simply doubleclicking the EXE file, you will get a nasty error. If you know that an error might occur, you should handle it. This is where exceptions are used. Here is a slightly modified version of the code from above:

Syntax:
staticvoid Main(string[] args)
{
      int[] numbers = newint[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();
}

Try running the program now, and see the difference - instead of Visual C# Express/Windows telling us that a serious problem occured, we get to tell our own story. But wouldn't it be nice if we could 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. We now tell which exception we want caught in this case the base of all exception, the exception. By doing so, we get some information about the problem which caused the exception.

As I said, exception is the most general type exception. The rules of exception handling tells us that we should always use the least general type of exception, and in this case we actullay know the exact type of exception generated by our code.

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

The result is as expected IndexOutOfRangeException. We should there for handle this exception, but nothing prevents us from handling more than one exception in some situation you might wish to do different things, depending on which exceptions was thrown simply change our catch block to the following.

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 look for the IndexOutOfRangeException first. If we did it the other way around, the catch block with the exception class would get it. Because all exceptions derive from it. So in other words you should use the most specific exception first.

One more thing you should know about concerning exception is the finally block. The finally block can be added to a set of catch block, or be used exclusively, depending on your needs. The code within the finally block is always run – exception or no exception. It’s a good block if you need to close file references or dispose object you won’t need anymore. Since our example have been pretty simple so for we have not really been in need of any cleanup, since the garbage collector handles that. But since will likely run into situations where you need the finally block, here is an extended version of our example:

int[] numbers = newint[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 both the first exception block and the finally block is executed. If you remove the line that adds the number 42 to the array, you will see that only the finally block is reached.

Another important part you should know about exceptions is how they impact the method in which the exception occure. Not all unhandled exceptions are fatal for your application but when they aren’t, you should not expect the remaining code of the method to be executed. On the other hand, if you do handle the exception, only the lines after the try block will be executed.


Check more posts on exceptions here


I am a content writter !

Leave Comment

Comments

Liked By