Hi everyone in this article I’m explaining about exceptionhandling in c# .net.
Details:
In every program, things go wrong sometimes. With C#, we'reblessed with a good compiler, which will help us prevent some of the mostcommon mistakes. Obviously it can't see every error that might happen, and inthose cases, the .NET framework will throw an exception, to tell us thatsomething went wrong. Let's bring the example:
Syntax:
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 running this example, and you will see what I'mtalking about. Do you see what we're doing wrong? We have defined an array ofintegers 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. Whenrun 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 shouldhandle it. This is where exceptions are used. Here is a slightly modifiedversion of the code from above:
Syntax:
static void Main(string[] args)
{
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();
}
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 whatwent wrong? No problem:
catch(Exception ex)
{
Console.WriteLine("An error occured: " + ex.Message);
}
As you can see we have added something to the catchstatement. We now tell which exception we want caught in this case the base ofall exception, the exception. By doing so, we get some information about theproblem which caused the exception.
As I said, exception is the most general type exception. Therules of exception handling tells us that we should always use the leastgeneral type of exception, and in this case we actullay know the exact type ofexception generated by our code.
Console.WriteLine("An error occured: " +ex.GetType().ToString());
The resultis as expected IndexOutOfRangeException. We should there for handle thisexception, but nothing prevents us from handling more than one exception insome situation you might wish to do different things, depending on whichexceptions 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);
}
Asyou can see, we look for the IndexOutOfRangeException first. If we did it theother way around, the catch block with the exception class would get it. Becauseall exceptions derive from it. So in other words you should use the mostspecific exception first.
One morething you should know about concerning exception is the finally block. The finallyblock can be added to a set of catch block, or be used exclusively, dependingon your needs. The code within the finally block is always run – exception orno exception. It’s a good block if you need to close file references or disposeobject you won’t need anymore. Since our example have been pretty simple so forwe have not really been in need of any cleanup, since the garbage collectorhandles that. But since will likely run into situations where you need thefinally block, 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. Timeto clean up!");
}
Console.ReadLine();
Ifyou run the code, you will see that both the first exception block and thefinally block is executed. If you remove the line that adds the number 42 tothe array, you will see that only the finally block is reached.
Anotherimportant part you should know about exceptions is how they impact the methodin which the exception occure. Not all unhandled exceptions are fatal for yourapplication but when they aren’t, you should not expect the remaining code ofthe 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
Leave a Comment