Exception Handling


Exceptions are unforeseen errors that happen in your programs. Programmers always detect and most of the time writes correct code to avoid all the errors or exceptions that can distract the execution of the code and cause unwanted results.

However, there are times when you don't know if an error will occur. For example, you can't predict when you'll receive a file I/O error, run out of system memory, or encounter a database error. These things are generally unlikely, but they could still happen and you want to be able to deal with them when they do occur. This is where exception handling comes in. When exceptions occur, they are said to be "thrown". What is actually thrown is an object that is derived from the “S ystem. Exception" class

Try/catch and Finally Block:

This is a way we can handle exceptions in C#.

* Try Block:- In this block, we include all the suspected code. This means the code that is most likely to cause exception.

* Catch Block:- In this block we include all handlers that will be take care of exception that occurs. We can have number of catch blocks associated to single try block.

* Finally Block : The finally block contains the cleanup code that we needed whether the code is succeed or not. Most of the time we write a code that will deal locate the memory that we associated in the beginning like memory allocated to connection object.


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;



public partial class Form14 : Form


public Form14()




private void button1_Click( object sender, EventArgs e)

{ //Simple Try/Catch Block

int dividebyZero = 0;

int a = 20;

int b = 0;



dividebyZero = (a / b);

}catch ( DivideByZeroException ex)


MessageBox .Show( "2nd EXCEPTION :: " + ex.ToString());

}catch ( Exception ex) {

MessageBox .Show( "EXCEPTION :: " +ex.ToString());



private void button2_Click( object sender, EventArgs e)

{ //Try,Catch and Finally Block

FileStream outputStream = null ;

FileStream inputStream = null ;

try {

outputStream = File.OpenWrite( "DestinationFile.txt" );

inputStream = File.OpenRead( "BogusInputFile.txt" );

}catch ( Exception ex) {

MessageBox .Show(ex.ToString());

}finally {

if (outputStream != null ) {


MessageBox .Show( "OutputStream Closed." );


if (inputStream != null ) {


MessageBox .Show( "InputStream Closed." );







  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: