Monday, 23 April 2018

04 Asp.Net Catching and Correcting errors

Catching and Correcting errors 
Before you go through the chapter, you need a clear concept about C# and its simple implementation. You need a clear concept of web page (.aspx) and controls.

                        Sometimes  program comes in a situation , where some unusual problem occurred during the execution of the logic .This is termed as exception. When the program is running and exception has occurred , the program display the exception to user. There may be a lot of  causes that leads to the exception. File me not found, index may be out of bound, casting or conversion error, loop is infinite  and many more.Here is some exception .

    • System.IO.IOException : Handles file input output errors.
    • System.IndexOutOfRangeException : Handles errors generated  when a method refers to an array index out of range.  
    • System.ArrayTypeMismatchException : Handles errors generated when type is mismatched with the array type.
    • System.NullReferenceException : Handles errors generated from referencing a null object.
    • System.DivideByZeroException : Handles errors generated from dividing a dividend with zero.
    • System.InvalidCastException :Handles errors generated during typecasting.
    • System.OutOfMemoryException :Handles errors generated from insufficient free memory.
    • System.StackOverflowException :Handles errors generated from stack overflow.

                              A smart programmer  will handle this exception in such a way , user will not be affected for this exception. Microsoft Visual Studio has option to handle  exception , through exception handling process . Sometimes  exception occurred , that is not  expected from the program , but the exception occurred , this kind of exception is called  unhandled exception.

                                Microsoft Visual Studio provide structure for handling exception ,this  structure is called  structure exception handling(SEH). A predefined template to handle exception is there , if error  occurred , redirect to a  error page or display proper message to user .

                          Below it is  the details of Keyword used in the exception handling structure.

try : try is the starting of exception handling structure followed by  bracket.The code, you need to handle the exception , should be  placed in try block. Try block start and end with "{}".
You can place, another exception handling structure under a try block. When a programe eounter and exception, threw it to the catch block. Below is the example of try block.


               try
                        {
                                   //your code goes here
                       }


catch : catch an exception in this blok. The starting and ending of this  block is enclosed by opening and closing parenthesis "{}". The exception are various type of exception, maybe file not found, maybe conversion error.
  
                       try
                      {
                            //your code goes here
                      }
                     catch (Exception ex)
                     {
                             //Exception handleing code goes here
                     }


finally : The resource used in the exception handling  , made them free in this part. Every program has to go through this block   exception has occurred or not.


                    try
                   {
                          //your code goes here
                    }
                    catch (Exception ex)
                   {
                         //Exception handleing code goes here
                   }
                   finally
                   {
                       // All code goes from here
                    }
end try :  End of exception handling structure.

Below is the example of exception handling. 

try
{
                 int a = 100;
                 int b = 0;
                 int c = 0;
                 c = a / b;

}
catch (Exception ex)
{
                  Response.Write(ex.ToString());
                //Exception handleing code goes here
}
finally
{
         // All code goes from here
}




You have written a  program, the program  divide a variable  with another variable. The second variable value is zero. In this case, divisible by zero error will be occur, exception is catched  as below.


                              There various types of exception  hanging provision in the. Net Framework. You can view the exception types of.Net framework as follows.

debug>> exception.

                                     Most of the exception  catch by. Net Framework smartly. You can create new exception in your application. This custom exception will  work same like inbuilt exception. This is called application exception . Your application exception class should always inherit system.Exception  base class. Below is the Below is the example of custom exception class and its application.

Custom Exception Class
class InvalidRegitrationNumberException : Exception
{
        public InvalidRegitrationNumberException()
        {

         }

public InvalidRegitrationNumberException(string name)
: base(String.Format("Invalid Registration Number: {0}", name))
    {
    }
}

Custom Exception Implementation

   try
   {
      int a = 100;
      int b = 0;
      int c = 0;
      c = a / b;
     }
    catch (InvalidRegitrationNumberException ex)
    {

    }
    finally
    {
      // All code goes from here
}


                     Another way to  handle exception through web object. Sometimes, exception handling structure not able  to catch  all the exception. ASP.NET provide alternative method to catch the exception and handle it.

Page_error:  An error occurred, but not handled by the exception handling structure in ASP.NET pages. The error can be handled from page error area.

Global_error: An error has occurred any where in the application, but not been handle by  exception handling structure. Error can be traced from  Global_error.Global error  method reside in Global.ascx pages.

Application_error: An error has occurred, has not been handled by exception handling  structure, can be handle form  application error. This method also resetting Global.ascx pages.

Using page error
As we discussed earlier exception that can be traced at the page level also, that is called page_error. You have to write the code in the page_error section.Below the sample of page error event.


private void Page_Error(object sender, EventArgs e)
{
          Exception ex = Server.GetLastError();

          if (ex is InvalidRegitrationNumberException)
          {
                  Server.Transfer("GenericErrorPage.aspx", true);
           }

}



You will notice, error has been  captured by  Server.GetLastError method.And finally  you have two ways, redirect to a message page  or  display message in the same page.Below is the example of displaying message in the same page.

private void Page_Error(object sender, EventArgs e)
{
         Exception ex = Server.GetLastError();

         if (ex is InvalidRegitrationNumberException)
          {
               Response.Write("
We have got some problem , please visit later
");
          }

}


As we have discussed earlier, you can catch exception of an application form Global error. Below is the example of an application  heroines catched  by  Global error.



An unhandled exception can be handle  from application error also. Below is the example of application error handle by the code.


void Application_Error(object sender, EventArgs e)
{
   // Code that runs when an unhandled error occurs
}

No comments:

Post a Comment

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

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