Pages

Wednesday, May 15, 2013

Exception Handling for C# Beginners

Exception is a run time error.
1.When CLR encounters unknow sitution then it can not execute future lines of code and it urbutly terminates the program
2.If we want to stop the ubrupt termination of the program we have to handle the exception or runtime error
3.In c# we can handle the exception by ussing try ,catch and finally block.
4.Every try block requred atleast one catch block or finally(one try -one catch or one finally block bound)
5.A try block may optionaly cantain multiple catch block.
6.All exception in .NET inherit directly inherit from Exception class
* Exception-----> application Exception
*Exception ---->system exception
7.when an exception arieses CLR looks for the coreresponding catch block in the method where exception is arised.If not  found CLR searches for the suitable catch block up in the call stack.If clr unable to find sutable catch block in the call stack then CLR will terminate the program from memory.

Syntax:

  try
    {
    suspected code
    }
    catch(Exception ex)
    {
    log exception
    }
    finally
    {
}

sample code:

public partial class Exception_handling : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            int a = Convert.ToInt32(txtA.Text);  //suspected code
            int b = Convert.ToInt32(txtB.Text);  //suspected code
            int c = a + b;
            Response.Write(c);
        }
        catch (Exception ex)
        {
            //Error
            Response.Write("program error");  //for showing msg
        }
    }
    protected void Div_Click(object sender, EventArgs e)
    {
        try
        {
            int a = Convert.ToInt32(txtA.Text);  //suspected code
            int b = Convert.ToInt32(txtB.Text);  //suspected code
            int c = a / b;
            Response.Write(c);
        }
        catch (Exception ex)
        {
            //Error
            Response.Write("program error");  //for showing error msg
        }
    }
}

No comments:

Post a Comment