Wednesday, 1 May 2013

Exception handling in C#


Exception handling in C#


Working with exception handling: 
1)compile time problems are called as errors 
  EX:syntax errors 
2)runtime problems are called as exceptions 
3)exception is a runtime condition, which stops the normal execution of a program abnormally 
4)when an exception is raised, Then program’s execution will be stopped automatically 
5)generally exceptions will be raised, while working with 

a)type casting 
b)files and database connections etc… 
c)memory

6)to work with exception handling, C# introduced 4 keywords they are 
  Try, catch, finally and throw 
7)syntax of try, catch & finally 
           try 
           {
                Line 1; 
               Line 2; 
               Line 3; 
            } 
           catch(CLASSNAME obj) 
          { 
          } 
          catch(CLASSNAME 2obj) 
          { 
          } 
          finally 
          { 
          }

8)if an exception is raised in line2(or ant line), Then remaining lines in that try block will not be executed 
9)try block must be followed either with one catch, many catches, one finally or All 
10)catch will be executed only when  exception is raised but finally will be executed always respective of an exception 
11)always catch takes an argument, which must be a class name 
12)to work with exception handling, .Net introduced ~400 predefined classes

Example on exception handling 
Open windows forms application project: 
Start->programs->Microsoft visual studio 2010->Microsoft Visual studio 2010->file menu->new-> 
project->select visual c# from installed templates->select windows forms application project     
place a textbox & button

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms;

namespace WindowsFormsApplication9 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
        }

        private void button1_Click(object sender, EventArgs e) 
        { 
              //code for button-click 
            try 
            { 
                int s=int.Parse(textBox1.Text); 
                s=s+1000; 
                MessageBox.Show("sal is:"+s); 
                string []x ={"c#","asp"}; 
                MessageBox.Show(x[1]); 
                MessageBox.Show(x[2]); 
                MessageBox.Show(x[0]); 
            } 
            catch(FormatException fe) 
            { 
                MessageBox.Show(fe.Message+"please enter only numbers"); 
            } 
            catch(Exception e1) 
            { 
                MessageBox.Show(e1.Message); 
            } 
            finally 
            { 
                MessageBox.Show("from finally"); 
            } 
        } 
    } 
} 

Execute the project F5

No comments:

Post a Comment