Pages

Wednesday, 22 July 2015

Throwing Exceptions

Throwing Exceptions

You can make your code explicitly raise an exception by using the throw statement. The syntax for the throw statement is the following:
throw [Exception Object];

For example, following code will throw exception when supplied file name and display file content when the file exist is not exist:
class Program
{
 static void readFile(string fileName)
 {
  if(File.Exists(fileName))
  {
   FileStream myFile = File.OpenRead(fileName);
   int data;
   do
   {
    data=myFile.ReadByte();
    if (data == -1)
     return;
    else
     Console.Write((char)data);
   }while(true);
  }
  else
  {
   throw new ArgumentNullException();
  }
 }

 static void Main(string[] args)
 {
  try
  {
   readFile("a.txt");
  }
  catch(ArgumentNullException)
  {
   Console.WriteLine("File not exist");
  }
 }
} 

Throwing Without an Exception Object

The throw statement can also be used without an exception object, inside a catch block with following restriction:
  • This form rethrows the current exception, and the system continues its search for additional handlers for it.
  • This form can be used only inside a catch statement.
For example, the following code rethrows the exception from inside the first catch clause:
class Program 
{
 public static void PrintArg(string arg)
 {
  try
  {
   try
   {
    if (arg == null)
    {
     ArgumentNullException myEx = new ArgumentNullException("arg");
     throw myEx;
    }
    Console.WriteLine(arg);
   }
   catch (ArgumentNullException e)
   {
    Console.WriteLine("Inner Catch: {0}", e.Message);
    throw;
   }
  } 
  catch
  {
   Console.WriteLine("Outer Catch: Handling an Exception.");
  }
 }

 static void Main() 
 {
  string s = null;
  PrintArg(s);
  Console.Read();
 }
}  

This code produces the following output:
Inner Catch: Value cannot be null.
Parameter name: arg
Outer Catch: Handling an Exception.

0 comments:

Post a Comment