Code normally doesn't work as expected. Failures do occur and will continue to as long as it's humans writing code. Some failures are even beyond the control of the programmer.
It's therefore imperative that applications be able to detect failures. And handle them gracefully. This is by taking the appropriate action to adjust to the failure. Or by reporting it to the user definitely.
Try Catch
C# makes it easy to seperate error-handling code from the logic code in your program. This is by using exceptions and exception handlers.
- We write code withing a try block. Such that an attepmt will be made to execute all the statements inside the try block. If an error occurs execution will jumpt out of the try block and into another piece of code designed to catch the exception.
- We write a catch handler. It can be one or multiple of them. We write them immediately after the
try
block. Each catch handler will capture and handle a specific type of exception. These exceptions will be for the different errors that can arise in thetry
block. If a statement within the try block causes an error then the runtime will throw an exception. It will then examine the catch handlers and transfer control directly to the first matching handler.
EXAMPLE
using System;
namespace ExceptionApp
{
class Program
{
static void Main()
{
show(-1);
}
static void show(int index)
{
string[] galaxies = { "Centaurus", "Whirlpool", "Messier 87", "Sombrero", "Cartwheel", "Leo" };
try
{
Console.WriteLine("Galaxy : {0}",galaxies[index]);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Exception : {0}",e.Message);
}
Console.Read();
}
}
}
RESULT
```shell
Exception : Index was outside the bounds of the array.
Clearly in the above example you can see we are specifying the type of exception to be caught in our catch handler. The IndexOutOfRangeException is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds.
We can then examine several properties of this IndexOutOfRangeException including Message
which we display in the console.
Catching Multiple Exceptions
You can not only catch one exception but multiple of them. You do this if there is a possibility that your code can raise different type of errors.
EXAMPLE
using System;
namespace ExceptionApp
{
class Program
{
static void Main()
{
show(-1);
}
static void show(int index)
{
string[] galaxies = { "Centaurus", "Whirlpool", "Messier 87", "Sombrero", "Cartwheel", "Leo" };
try
{
Console.WriteLine(Convert.ToInt32("Hello World"));
Console.WriteLine("Galaxy : {0}", galaxies[index]);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Exception : {0}", e.Message);
}
catch (FormatException e)
{
Console.WriteLine("Exception : {0}", e.Message);
}
Console.Read();
}
}
}
RESULT
Exception : Input string was not in a correct format.
In the above example, the FormatException is raised when we try to convert a String Hello World
into an integer. It gets caught first given the conversion statement comes first before us attempting to access our array element.
The moment an exception occurs control gets immediately transfered to its appropriate catch handler.