Home > DeveloperSection > Blogs > Exception Handling in C#

Exception Handling in C#


C# C# 
Ratings:
1 Comment(s)
 1997  View(s)
Rate this:

ExceptionHandling in C#.Net

Handling of error occurring atRun-time is known as Exception handling. Exception handling is a way to preventapplication from crashing.

C# provides three keywords to handleexceptions.

·        try

·        catch

·        finally

Thetry block

The lines of code which we think cangenerate error; we put them in try block. If exception is raised codecompilation is transferred to catch block.

Thecatch block

When exception occurs codecompilation is transferred to catch block and code inside catch block isexecuted. We can have more than one catch block for one try block.

Thefinally block

Finally block is executed after tryblock regardless of the occurrence of error. Finally block contains all cleanupcodes. For example, if there is no need of open connection to the databaseafter try block we can write code for connection close in finally block.

Example

This code is written inside tryblock, as there is possibility that we could be trying to insert same recordalready present in database with unique attribute or connection to the databaseis not open.

try

           {

               System.Data.SqlClient.SqlCommandBuilder cb;

               cb = new System.Data.SqlClient.SqlCommandBuilder(da);

               DataRow dr = dt.Rows[count];

               dr[0] = txtId.Text;

               dr[1] = txtName.Text;

               dr[2] = txtAddress.Text;

               da.Update(ds, "Employee");

               MessageBox.Show("DataUpdates");

           }

Catch block will catch any erroroccurred in try block and display message box with exception detail.

           catch (Exceptionex)

           {

               MessageBox.Show(ex.Message);

           }

Finally block will be executedregardless of error occurred or not.

           finally

           {

               con.Close();

           }

 


Exception handling

By Chris S on   5 years ago
try
{
Statement 1 - Open database
Statement 2 - Execute Query
}
catch(Exception ex)
{
Statement 3 - Show messagebox to user
}
finally
{
Statement 4 - Close Database
}

Don't want to miss updates? Please click the below button!

Follow MindStick