Unit 4
Unit 4
UNIT-IV
EXCEPTION HANDLING
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords: Try, Catch, Finally and Throw.
Try: A Try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more Catch blocks.
Catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The Catch keyword indicates the catching of an
exception.
Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed whether an
exception is raised or not.
Throw: A program throws an exception when a problem shows up. This is done using a
Throw keyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a combination of
the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an
exception. Code within a Try/Catch block is referred to as protected code, and the syntax for
using Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.
Exception Classes in .Net Framework
In the .Net Framework, exceptions are represented by classes. The exception classes in .Net
Framework are mainly directly or indirectly derived from the System.Exception class. Some of
the exception classes derived from the System.Exception class are
the System.ApplicationException andSystem.SystemException classes.
The System.ApplicationException class supports exceptions generated by application
programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the error-
handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Delegates are pointers that are used to store and tranfer information like the memory address,
event handled by functions and subroutines. Delagates are type safe, since they check for the
signatures of functions and subroutines only if same, they transfer information. A delegate is
declared using the keyword Delegate to a function or procedure name.
Example:
Module Module1
Public Delegate Function del1(ByVal x As Integer,
ByVal y As Integer) As Integer
Public Delegate Sub Display()
Class deleg
Public Sub Disp()
Console.WriteLine("Method inside the Class")
End Sub
End Class
Sub Main()
End Module
Result:
30
200
Method Inside Class
Description:
In the above Delegate example del1 is a delegate that gets two integer arguments and return an
integer. Using this delegate with the keyword AddressOf the values stored in the memory
location of the procedures check and multi are retreived.
Using the delegate Display the sub procedure Disp() inside the class deleg is also displayed.
The AddressOf operator creates a function delegate that points to the function specified
by procedurename. When the specified procedure is an instance method then the function
delegate refers to both the instance and the method. Then, when the function delegate is invoked
the specified method of the specified instance is called.
EVENTS
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system
generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of events. An
event is an action that calls a function or may cause another event.
Mouse events
Keyboard events
Mouse events occur with mouse movements in forms and controls. Following are the various mouse events related
with a Control class:
Following are the various keyboard events related with a Control class:
KeyDown - occurs when a key is pressed down and the control has focus
KeyPress - occurs when a key is pressed and the control has focus
KeyUp - occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs
EXAMPLE
Add the above mentioned controls and add the following mouse events code.
The sender arguement is often more useful if you instantiate an object using it. For
example, if you are processing a Button control:
ADO.NET
Every organization maintains data storage for its business, employees and clients.
This data must be easily accessible and updateable.
The machine in which the backend database is stored is known as server.
This Database can be accessed and used by front end applications through some
connectivity.
The machine in which the application run is known as client.
Previously ODBC was used for this purpose.
ODBC – open database connectivity local/remote.
ADO – Active Data Object
It is defined as object model.
It comprises of objects, methods and properties.
Methods – Access and update Data Sources.
Properties – Control the behavior of the method.
ADO.NET OBJECT MODEL
Connection Environment
.NET DATA PROVIDER
We know that ADO.NET allows us to interact with different types of data sources and
different types of databases.
However, there isn't a single set of classes that allow you to accomplish this universally.
Since different data sources expose different protocols, we need a way to communicate
with the right data source using the right protocol.
Some older data sources use the ODBC protocol, many newer data sources use the OleDb
protocol, and there are more data sources every day that allow you to communicate with
them directly through .NET ADO.NET class libraries.
ADO.NET provides a relatively common way to interact with data sources, but comes in
different sets of libraries for each way you can talk to a data source.
These libraries are called Data Providers and are usually named for the protocol or data
source type they allow you to interact with.
Table 1 lists some well known data providers, the API prefix they use, and the type of
data source they allow you to interact with.
Table 1. ADO.NET Data Providers are class libraries that allow a common way to interact with specific
data sources or protocols. The library APIs have prefixes that indicate which provider they support.
API
Provider Name Data Source Description
prefix
ODBC Data
Odbc Data Sources with an ODBC interface. Normally older data bases.
Provider
OleDb Data
OleDb Data Sources that expose an OleDb interface, i.e. Access or Excel.
Provider
Oracle Data
Oracle For Oracle Databases.
Provider
SQL Data
Sql For interacting with Microsoft SQL Server.
Provider
Borland Data Generic access to many databases such as Interbase, SQL Server,
Bdp
Provider IBM DB2, and Oracle.
Connection Object
These objects are used to create a connection to the database for moving data between the
database and user application.
The connection can be created using.
SQL Connection Object
Open (), close (), and dispose () are the methods of connection object used to open and close the
defined connection.
Dim conn As SQLConnection
conn = New SQLConnection ()
conn.connectionstring =”datasource =asdf; initial catalog =stud; userId =sa; pwd =123”
conn.open ()
Datasource is the name of the SQL server which is to be connected.
Initial Catalog is the name of the database.
Used Id is the SQL server login account and pwd is the password.
The user must close the connection after using it. This is done by either close (or) dispose
method.
conn.close ()
Command Objects
These command objects are used to read, add, update and delete records in a database.
These operations are done by sql command objects.
Methods: Execute Reader ()
Execute Non Query ()
Properties: connection, command text.
Execute Reader () method is used to execute the commands and retrieve rows from the database.
Execute Non Query () method is used to execute the command without retrieving any row.
Dim conn As sqlconnection
Dim comm As sqlcommand
comm. = New sql command ()
comm.connection = conn
comm.commandText = “select * from Stud Table”
Data Reader Objects
These objects are used to read row wise data in read only format from databases. Sql
Data Reader object is used.
Execute Reader () – is used to retrieve a row from database.
Read () – is used to obtain a row from the result of the query.
Get String () – is used to access a column value in a selected row.
Close () – must be called after the use of Data Reader Objects.
Example:
Dim conn As Sqlconnection
Dim comm As Sqlcommand
Dim rd As SqlDataReader
conn = New Sqlconnection ()
conn = New Sqlconnection ()
conn.connection string = “Datasource = asdf; Initial catalog =college; UserId =sa; pwd
=123”
conn.open ()
comm = New Sqlcommand ()
comm.connection = conn
comm.commandText = “select * from staff”
rd = comm.ExecuteReader
Dataset is a temporary storage of records. The dataset represents a complete set of data including
tables and their relationships.Dataset must contain atleast one data table object in its data table
collection.
Each Data Table contains both a
1. Data Row Collection
2. Data Column Collection
Objects of Datasets are
1. Data Table Collection
2. Data Tables
3. Data Row Data Adapter Objects
Fig 4.3 Disconnected Environment
SqlDataAdapter OBJECT
This object is used to exchange Data between a database and a Dataset. It reads data from the
database to the dataset and then writes the changed data back to the database.
Properties:
Select Command (Accessing Rows in a Database)
Insert Command (Inserting rows in the Database)
Update Command (For modifying rows in the Database)
Delete Command (For deleting rows)
FILL Method:
It is used to write the result of select command into the dataset.
Example:
Dim Myadapter As New SqlDataAdapter
Myadapter.select command = mycomm
Dim Mydataset As New Dataset ()
Myadapter.Fill (Mydataset, stud Table)
conn.close ()
Data Table Collection Object:
It is used to provide one or more tables represented by data Table object. It contains collections
such as Data Column Collection, Data Row Collection.
Data Table Object:
It contains a single table of memory resident data. It contains a collection of rows represented by
Data Row Collection, a collection of columns represented by data Column collection.
Data Row Object:
It contains methods and propeties, to retrieve, insert, delete and update the values in the Data
Table.
Add () – Add a new Data Row in the Data Collection.
Remove () – Delete a Data Row from the Data Row Collection
Accept Changes () – Confirm the Addition.
New Row () – Add New Row.
EXAMPLE
POPULATING COMBO BOX WITH SOURCE CITY NAMES DATASET
note:
1. Create a database with table containing two fields source_id,source_name and enter
some city names.
2. In c# window form put a combo box and in form load enter the following coding
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "source_id";
comboBox1.DisplayMember = "source_name";
}
}
}