Exception Handling :

May 11, 2011
  • Exception is a runtime error which arises because of abnormal condition in a code sequence.
  • The exceptions are defined as the anomalies that occur during the execution of a program. Which can be because of the user, logic or system failure/error.
  • If a user or programmer does not provide a proper procedure to handle these anomalies or exceptions, then the .NET run time environment provide a default procedure, which terminates the current execution of that program .
  • Exception handling is an in built mechanism in .NET framework to detect and handle run time errors.
  • try, catch and finally are block which are used to handle the exceptions in .Net.
  • The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.
  • If during exception of program no exception is occurred inside the try block, then the control is directly transferred to finally block.

Examples of Exceptions :

  • System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException
Below code will terminate the program after exception is thrown. public class Exception_Handling { public static void Main(string[] args) { int first = 0; int second = 100 / first; Console.WriteLine(second); } }
Below code will run after the exception is raised or thrown by program. public class Exception_Handling { public static void Main(string[] args) { int first = 0; int second = 0; try { second = 100 / first; Console.WriteLine("This code line is not executed"); } catch (DivideByZeroException de) { Console.WriteLine(de.ToString()); } Console.WriteLine("Result of Division :- {0}", div); } }