Exceptions and Exception Handling in C#

EXCEPTION HANDLING

C#-exception

                                  Exception Handling is one of the advanced topics in c#. Here we can see the basics information about the exceptions and exception handling methods. Before entering into the topic we must know what is exceptions? and how we can handle it?.

   Exceptions means a person or thing that is excluded from a general statement or does not follow a rule. In our programming side we may refer it as syntax or program flow. In these cases we use Exception handling method to overcome or to know the errors

   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.

Syntax

try
{
// Code to try goes here.
}
catch ()    //  catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
// Never catch base class System.Exception without
// rethrowing it at the end of the catch block.
}
finally
{
// Code to execute after the try block goes here.
}

Some of you will still have doubts on what the exception really is. You can try the below program and get to know how it works.

EXAMPLE:1

using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[3];
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 8;
numbers[3] = 2;
foreach(int i in numbers)
Console.WriteLine(i);
Console.ReadLine();
}
}
}

You can now see what I’m talking about. Do you see what we’re doing wrong? We have defined an array of integers with room for 3 items, yet we try to use 4 spaces in it. Obviously, this leads to an error. If you want to find out the error or try to show an exception to execute the program means you can use the exception handling method.

Example:2

using System;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[3];
try
{
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 8;
numbers[3] = 2;
foreach(int i in numbers)
Console.WriteLine(i);
}
catch
{
Console.WriteLine("Something went wrong!");
}
Console.ReadLine();
}
}
}

You can see the difference here. This is try-catch block which explains you that there is something goes wrong. But here you will only know there is a problem but you may not identify what is the problem here?. Lets make our exception handling process to show whats the error occurring in our program.

Example:3

using System;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[3];
try
{
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 8;
numbers[3] = 2;
foreach(int i in numbers)
Console.WriteLine(i);
}
catch(Exception ex)
{
Console.WriteLine("An error occured: " + ex.Message);
}
Console.ReadLine();
}
}
}

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 exceptions, the Exception. By doing so, we get some information about the problem which caused the exception, and by outputting the Message property, we get an understandable description of the problem.In this case, we actually know the exact type of exception generated by our code.

There are also other methods in which we can identify the system identification error. By this we can use the exact same class for exception in our further codes.

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

We can get the system response code as IndexOutOfRangeException.In some situations you might wish to do different things, depending on which exception 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);
}

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 exceptions first.

One more thing you should know about concerning exceptions is the finally block. The finally block can be added to a set of catch blocks, or be used exclusively, depending on your needs. The code within the finally block is always run – exception or no exception. By this we can make many advanced functions like closing the file, deleting unwanted obj etc…

Example:4

using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[3];
try
{
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 8;
numbers[3] = 2;
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();
}
}
}

This will show you how the finally block works. For more details you can run the below program which has no exceptions but uses the finally block here.

Example:5 With No exception

using System;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[3];
try
{
numbers[0] = 5;
numbers[1] = 10;
numbers[2] = 8;
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();
}
}
}

Hope you have an idea on exception handling now…. Still to update the throw block…

Thanks to MSDN and csharp.net-tutorials…….

Advertisements

One thought on “Exceptions and Exception Handling in C#

  1. Together with almost everything which appears to be developing inside this specific subject material, your perspectives are somewhat radical. On the other hand, I appologize, because I can not subscribe to your whole theory, all be it exhilarating none the less. It would seem to everyone that your remarks are not completely rationalized and in reality you are generally your self not fully confident of the assertion. In any event I did take pleasure in reading it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s