Friday, 26 August 2016

Chapter-10 Exceptions Handling Part-1







A principle advantage of exception handling is that it automates much of the error handling code that previously had to be entered “by hand” into any large program.
Another reason that exception handling is important is that C# defines standard exceptions for common program such as divide by zero.



1.    An exception is an erroneous situation that occurs during program execution.
2.   When an exception occurs in an application, the system throws an error.
3.   The error is handled through the process of exception handling.
4.   There are three types of errors that can occur in the application: 

a)  Syntax errors: Occurs when statements are not constructed properly, keywords are misspelled, or punctuation is omitted.
b) Run-time errors: Occurs when an application attempts to perform an operation, which is not allowed at runtime.
c)  Logical errors: Occurs when an application compiles and runs properly but does not produce the expected results.

Syntax Errors

Class demo
                {
                Console.WriteLine(“Syntax Error”)//This is Syntax error
                }

Run-Time Errors

Class demo
                {
                Public void Calculate()
                  {
                                Int Num1,Num2, Result;
                                Num1=10; Num2=2;
                                Result=Num1/Num2;//This Run-Time Error
                  }           
                }

Logical Errors

Class demo
                {
                Public void Calculate()
                  {
                                Int Num1,Num2, Result;
                                Num2=10; Num1=2;
                                Result=Num1/Num2;//This Logical Errors
                  }           
                }

Exception Classes

There are many exception classes which are directly or indirectly derived from the System.Exception class.  Some of these classes are:

a)         System.ApplicationException class
b)         System.SystemException class

 The System.SystemException acts as a base class for all the predefined system exceptions. The following table describes some of the classes derived from the System.SystemException class.

Exception Classes
Description
System.IO.IOException
Handles I/O errors
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array element, which is out of its bound
System.NullReferenceException
Handles errors generated during the process of
dereferencing a null object
System.DivideByZeroException
Handles errors generated during the process of dividing the dividend with zero
System.InvalidCastException
Handles errors generated during typecasting
System.OutOfMemoryException
Handles memory allocation to the application errors

Exception Handling Fundamental

C# exception Handling works with four keywords : try, catch, throw and finally.

Program statement that you want to monitor which may cause error contained within Try block. If the exception occurred in try block exception throw to catch block and handle it. System generated exception are automatically thrown by try block but in case to generate manually exception we use throw keyword.

Handling Exceptions

a)  In exception handling, the application is divided into blocks of code.
b)   A block that shows the probability of raising an error contains one or more exception handlers.
c)   The exception handlers follow a control structure and a uniform way of handling the system level and application level errors.
d)  The blocks for exception-handling can be implemented using the following keywords:
             i)    try
             ii)    catch
             iii)  finally

   The try block:
1)   Core of exception handling are try and catch .Both keywords works together.You cannot use try block without catch
2)  The try block guards statements that may throw an exception. Following is the syntax of try block statement:

try
{
//statements that may cause an exception
}
catch(Exception ex)
{
}
catch(Exception ex2)
{
}

3)  The try block governs statements that are enclosed within it and defines the scope of the exception-handlers associated with it.
4)  A try block must have at least one catch block.
5)  When the exception occurred ,it is caught by the respective catch bock ,then it process the exception.
6)  To create the exception object is optional .You can directly use the exception without creating Object.

try{
}
catch {
}

The catch block:

1)  The catch statement of the catch block takes an object of the exception class as a parameter, which refers to the raised exception.
2) You can associate an exception-handler with the try block by providing one or more catch handlers, immediately after the try block

The finally block:
The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown:

try
{
   //statements that may cause an exception
}
catch (…)
{
                //error handling code
}
finally
{
                //statements to be executed
}

Demo of Exception Handling

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoException
{
    class Demo
    {
        public void Show()
        {
            int[] num = new int[4];
            try
            {
                Console.WriteLine("Before the exception is generated");
                for(int i = 0; i <10;i++)
                {
                    num[i] = i;
                    Console.WriteLine("Value of num[{0}] :{1}", i, num[i]);
                }
                Console.WriteLine("End of For loop");
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception occured : Index out of bound");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Demo d = new Demo();
            d.Show();
            Console.ReadLine();
        }
    }
}


Summary:-

1)   A logical error occurs when an application compiles and runs properly but does not produce the expected results.
2)  Exceptional conditions arise when an operation cannot be completed normally during the processing of C# statements and expressions.
I hope that the functionality of the above attribute is clear to you now. Now you can use this code in your application If you have further question, just drop a line below and I will try to answer you as soon as possible.

      Last but not least, connect with me on Twitter , Facebook , LinkedIn and Google+ for technical updates and articles news. We won’t spam or share your email address as we respect your privacy.





No comments:

Post a Comment