try
{
.........
}
catch (<exceptionType> e)
{
...........
}
finally
{
..........
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[ ] args)
{
int[ ] intArr = new int[5];
try
{
Console.WriteLine("Try block started.");
// Below code will generate an index out-of-bounds exception.
for (int i = 0; i < 8; i++)
{
intArr[i] = i;
Console.WriteLine("arr[{0}]: {1}", i, intArr[i]);
}
Console.WriteLine("Exception occured, this won't be displayed");
}
catch (IndexOutOfRangeException e)
{
// Catch the exception.
Console.WriteLine("\n ERROR :"+e.Message);
Console.WriteLine("\n SOURCE :" + e.Source);
}
finally
{
Console.WriteLine("Finally block.");
}
Console.WriteLine("After finally block.");
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int [ ] firstArr = { 3,9,18,36,72,144,288,576 };
int [ ] secondArr = { 3, 0, 6, 6, 0, 9 };
for (int i = 0; i < firstArr.Length; i++)
{
try
{
Console.WriteLine(firstArr[i] + " / " +
secondArr[i] + " is " +
firstArr[i] / secondArr[i]);
}
catch (DivideByZeroException e)
{
Console.WriteLine("ERROR : "+e.Message);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("ERROR : " + e.Message);
}
}
Console.ReadLine();
}
}
}
catch(Exception e)
{
// Your code here.
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 0;
try
{
Console.WriteLine("Outer try block");
try
{
Console.WriteLine("First inner try block");
int z = x / y;
}
catch (ArithmeticException e)
{
Console.WriteLine("Error from first inner try block");
Console.WriteLine("ERROR : "+e.Message);
}
try
{
int[] a = new int[3];
a[3] = 40;
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine ("Error from second inner try block");
Console.WriteLine ("ERROR : " + e.Message);
}
}
catch (Exception e)
{
Console.WriteLine ("Error from outer try block");
}
Console.WriteLine ("Control outside the main try block");
Console.ReadLine ();
}
}
}
using System;
namespace ConsoleApplication1
{
public class CustomException : Exception
{
//Throw exception with out message
public CustomException()
{
Console.WriteLine("Divide by zero exception occured");
}
//Throw exception with simple message
public CustomException(string message)
: base(message)
{
//put your custom code here
}
}
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Eneter the integer value");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Eneter the divisior");
int y = Convert.ToInt32(Console.ReadLine()); ;
if(y==0)
{
throw new CustomException();
}
else
{
int z = x / y;
Console.WriteLine ("Division of {0} / {1} is = {2}", x,y,z);
}
}
catch (CustomException ex)
{
Console.WriteLine ("Error found in application:" + ex.Message);
}
Console.ReadLine ();
}
}
}