Pages

Wednesday, 22 July 2015

About Exception

About Exception

An exception is a runtime error in a program that violates a system or application constraint, or a condition that is not expected to occur during normal operation. Examples are when a program tries to divide a number by zero or tries to write to a read-only file. When these occur, the system catches the error and raises an exception.

If the program has not provided code to handle the exception, the system will halt the program. For example, the following code raises an exception when it attempts to divide by zero:
   
static void Main()
{
 int x = 10, y = 0;
 x /= y;     // Attempt to divide by zero raises an exception
}

When this code is run, the system will halt and displays Unhandled Exception error message.

The try Statement

The try statement allows you to designate blocks of code to be guarded for exceptions and to supply code to handle them if they occur. The try statement consists of three sections:
  • The try block contains the code that is being guarded for exceptions.
  • The catch clauses section contains one or more catch clauses. These are blocks of code to handle the exceptions. They are also known as exception handlers.
  • The finally block contains code to be executed under all circumstances, whether or not an exception is raised.

See following code sample:
static void Main(string[] args)
{
 int x = 10, y = 0;
 try       //try block
 {
  Console.WriteLine("Try deviding by Zero");
  x /= y;
 }
 catch (Exception e)   //catch block
 {
  Console.WriteLine("Exception Catched: " + e.Message);
 }
 finally      //finally block
 {
  Console.WriteLine("Program is Terminated");
 }
}

The code will produce following display:
Try deviding by Zero
Exception Catched: Attempted to divide by zero.
Program is Terminated

0 comments:

Post a Comment