C Sharp/Exceptions

Exception Handling is a main feature of OOP Concepts. Before going to know about this Exception Handling we should know what is an Exception?. An exception is a runtime error which occurs while executing the program. Due to this our system may hang or happen some thing. Example:- if we are writing a program to divide two numbers. Suppose we have been given the fist integer as 4 and the other as 0. In situations like this the compiler don't know what to do. The system may hang. To overcome these types of situations (exceptions (runtime errors)) exception handling methods were implemented. The above example exception is called an Arithmetic Exception. Like this we have so many exception handling methods.

For the purpose of Exception handling we will use 4 key words. They are try, catch, throw, finally. In this 4 key words try key word is used to monitor the exceptions which are there in our code. This try key word contains the body. This block will be called as try block. We use to write our code in try block which may generates the exceptions. The try block will be as follows.

try
{ 
    Statement 1;
    Statement 2;
    - - - - - -
    - - - - - - 
    - - - - - -
}

The statements which are in the try block is called as body of the try block. When it monitor the exceptions then those exception will be thrown. Then the exceptions will be caught by catch block. Followed by the try block catch block should be there. This block can be the optional. A try block can have zero or more number of catch blocks. The catch block syntax will be as follows.

catch (parameters)
{
    Exception statement 1;  
    Exception statement 2;
    - - - - - - - -- - - 
    --------------------

}

From the above syntax catch block contains the arguments in that the data type will be treated as the class and the object will be treated as the variable like a common method.

Example :

int Division(int a, int b)
{
    try
    {

        return (a / b);
    }
    catch (System.DivideByZeroException dbz)
    {
        System.Console.WriteLine("Division by zero attempted!");
        return 0;
    }
}