Monday, 5 March 2018

018 C # tutorial Exception Handling

Exception handling :
You have written a program and successfully compile it. You have successfully tested your program also. During run time it may experience error. Even your code is fine, no Syntax error, testing also passed, still may error during run time. .Net provider structure for handling run time exception , this facility handle the error and continue the program without any obstacle.


try
         {
         }
catch
       {
       }
finally
      {
      }

                                              . Net exception handling comes under the namespace
System.Exception. All exception classes, maybe system define class or maybe custom class comes under the namespace System.Exception.
This facilates  
  •  A message to be human readable format.
  •  Tracing trace the particular point  from where the error  occured. 

An exception Handler have some particular method or area to handle the method. Any method or part of a method can throw exception, it may due to file access problem, divided by zero, variable not initialized and many more. Exception Handler syntax is as below.

Try : You have to put statement  of code in the try block . Try block wrap the code who is we need to associate any exception Handler. If any statement throw exception, the exception is thrown to the exception block in the method of "bubbling". If any error is occurred the handler will try to solve in the Handler, if not solve it will through the error again. Here is the example of try block.


try
    {
    //your code goes here
  }
Catch : The next part of an exception handler is catch block. Catch block works only when  any exception is occured  in the try block. In an exception Handler, there may be one or more catch block. Catch block will be written to handle the type of  exception need to be handled. There are several type of error can be occured. As we have discussed earlier there may be file access problem, divisible by zero problem.   So that ,the exception  may be of different type , null reference exception, argument null exception , divisible by zero exception. We can specify catch block to catch a specific exception. We can define our custom   user defined exception also. All this exception classes comes under the class System.exception. System.exception action will catch all the  exception of a program.

Example 1
try
           {
           //your code goes here
          }
catch(System.NullReferenceException e)
        {
         //Null Reference Handled
         }
catch (System.Exception ex)
       {
       //All exception
       }

Finally : Finally execute each time ,exception occured or not. Every code  goes through the try statement, will have to go through the final statement. We can  write  final block without catch block also. Here is the example of finally block.

Example 1
try
        {
         //your code goes here
        }
finally
        {
       }

Example 2
try
        {
         //your code goes here
        }
catch (System.ArgumentNullException e)
      {
      }
finally
     {
       //All Code Must be goes here
       //Execute All Time
   }


Nested Exception handler : Exception handler can be nested type also, a exception Handler contain another exception Handler. In this case , if the innermost exception handler fail to handle any error,  the immediate period will try to handle the error. Here is the example of nested exception Handler.



Example 1
try
        {
       //Nested Exception Handler
           try
              {
               //Your Statement
             }
            catch (System.ArgumentNullException e)
           {
           }
}
catch (System.Exception ex)
{
}
finally
{
         //All Code Must be goes here
         //Execute All Time
}


Custom exception or user defined exception : You can create a custom exception will the help of
System.ApplicationException class.  By inherit  System.ApplicationException exception class, a class will get all the required like message,  stack trace, inner exception properties etc. Now, you can custom you exception as required. Here is the example of custom exceptions.

 Example 1
public class MyCustom :System.ApplicationException

{

          public MyCustom(string message) : base(message)

           {

           }

}




try

       {


       }

catch (MyCustom ex)

     {

       Console.WriteLine("MyCustom: {0}", ex.Message);

    }

catch (Exception ep)

   {

   }

Rethrowing Exceptions : Writing an exception Handler is a tricky job, you may or may not catch and handle an exception in the  catch block. If an error is handled in catch block, then it is ok. Sometimes error cannot be handle in a particular catch blocks.  Then you need to exemption to handle outside of this catch block. Here is the example of throwing an exception when it is not handled by the catch blocks. While through throwing an exception, you can  pass additional information to the next application level.

Example 1
try
        {
        }
catch (System.ArgumentNullException e)
        {
         //Check if it can be handled
         throw e;
        }
finally
      {
      }
 Example2


try
        {
       }
catch (System.ArgumentNullException e)
     {
throw new NullReferenceException("I am getting error", e);
     }
finally
    {
   }
Here are some inbuilt exception class on .Net
  • System.IO.IOException : Handle file Input , Output error.
  • System.IndexOutOfRangeException : Handles array index out of range.
  • System.ArrayTypeMismatchException : Handles when type is mismatched with the array type.
  • System.NullReferenceException : Handles errors of null object.
  • System.DivideByZeroException : Handles errors when divided with zero.
  • System.InvalidCastException : Handles errors during typecasting.
  •  System.OutOfMemoryException : Handles errors of insufficient free memory.
  • System.StackOverflowException : Handles stack overflow error.  


Below are some example of exception handling of different type.
InvalidCastException  is a type of exception derived from System.Exception class. It handle error during the casting operation. The example shows that, you are converting Boolean to character which is impossible, the program is throwing error. The erroris is catched by InvalidCastException .

Example 1


bool flag = true;

try

        {

         char i = Convert.ToChar(flag);       

        }

       catch (InvalidCastException)

       {

          Console.WriteLine("Invalid cast from 'Boolean' to 'Char'");

      }

Example 1 
OutOfMemoryException  is a kind of exception which handle The error if out of memory occure . That is, there is no memory for the variable, and system is trying to access the memory Zone.The examples who's that String builder has in memory and we are going to insert extreme string position, and system is generating  exception.
StringBuilder sb = new StringBuilder(15, 15);

sb.Append("Hellow world");


try

   {

     sb.Insert(0, "I Am Learing C#", 1);

   }

  catch (OutOfMemoryException ex)

{

        Console.WriteLine("Out of Memory: {0}", ex.Message);

     //Insufficient memory to continue the execution of the program.

}


IndexOutOfRangeException  : a kind of exception , when is program access out of the the lower and upper bound range of an array. Below example array Range 100, program is trying to access 200 position. System is generating exception IndexOutOfRangeException
Example 1
try

       {

       int[] arr = new int[100];

       arr[0] = 1;

       arr[10] = 2;

       arr[200] = 3;

     }

catch (System.IndexOutOfRangeException ex)

    {

      //Index was outside the bounds of the array.

   }



No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...