C# Exception handling
C# provides
try...catch block to catch any errors that may occur during
programs execution. In the below example, we use the try...catch block to
catch the error that is comes from trying to access an element of the array by
using its index which in fact the element does not exist.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr = {1, 2, 3, 4, 5};
int i;
try{
for(i=0;i<=arr.Length ;i++)
Console.WriteLine(arr[i]);
}catch(IndexOutOfRangeException e){}
}
}
}
The IndexOutOfRangesException is an exception class
for handling the error that is generated from accessing an element that does
not exist in an array.
If you are not sure the types of errors to be catch you
can use the Exception class. The code above can be rewritten to:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr = {1, 2,
3, 4, 5};
int i;
try{
for(i=0;i<=arr.Length ;i++)
Console.WriteLine(arr[i]);
}catch(Exception
e){}
Console.Read();}
}
}
If you want to show a friendly message when an error
occurs, you can write the message in catch(){message} block.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] arr =
{1, 2, 3, 4, 5};
int i;
try
{
for (i = 0; i <= arr.Length; i++)
Console.WriteLine(arr[i]);
}
catch
(Exception e) { Console.WriteLine("You may access an array
element that doesn't exist."); }
Console.Read();
}
}
}
Using finally keyword
The finally keyword is used to execute lines of code in
its block regardless to the errors that may occur. The code in its
block(finally{code}) will always execute whether an error exists or not.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
public static int pos=0;
static void Main(string[] args)
{
int[] arr = {1, 2, 3, 4, 5};
int i;
try
{
for (i = 0; i <= arr.Length; i++)
Console.WriteLine(arr[i]);
}
catch (Exception e) { }
finally
{
Console.WriteLine("The program ended...");
}
Console.Read();
}
}
}
|
|
-
Why and How to learn
- C programming language?
- C++ programming language?
- C# programming language?
- Java programming language?
- Python programming language?
- VB programming language?
|
|