0% found this document useful (0 votes)
27 views16 pages

Unit 4

The document discusses exception handling in VB.Net. It describes the keywords Try, Catch, Finally and Throw used for exception handling. It also provides examples of throwing exceptions and handling them using Try/Catch blocks. The document further discusses delegates, events and ADO.Net.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views16 pages

Unit 4

The document discusses exception handling in VB.Net. It describes the keywords Try, Catch, Finally and Throw used for exception handling. It also provides examples of throwing exceptions and handling them using Try/Catch blocks. The document further discusses delegates, events and ADO.Net.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

PLATFORM TECHNOLOGY

UNIT-IV

EXCEPTION HANDLING

An exception is a problem that arises during the execution of a program. An exception is a


response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

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:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0
Delegates in vb.net

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()

Public Function check(ByVal x As Integer,


ByVal y As Integer) As Integer
Return (x + y)
End Function

Public Function multi(ByVal x As Integer,


ByVal y As Integer) As Integer
Return (x * y)
End Function

Class deleg
Public Sub Disp()
Console.WriteLine("Method inside the Class")
End Sub
End Class

Sub Main()

Dim a As New del1(AddressOf check)


Dim b As New del1(AddressOf multi)
Dim ob As New deleg
Dim c As New Display(AddressOf ob.Disp)
Console.WriteLine(a(10, 20))
Console.WriteLine(b(10, 20))
c()
Console.Read()
End Sub

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.

Event handlers are functions that tell how to respond to an event.

VB.Net is an event-driven language. There are mainly two types of events:

 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:

 MouseDown - it occurs when a mouse button is pressed


 MouseEnter - it occurs when the mouse pointer enters the control
 MouseHover - it occurs when the mouse pointer hovers over the control
 MouseLeave - it occurs when the mouse pointer leaves the control
 MouseMove - it occurs when the mouse pointer moves over the control
 MouseUp - it occurs when the mouse pointer is over the control and the mouse button is released
The event handlers of the mouse events get an argument of type MouseEventArgs

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.

Public Class Form1


Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub
Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub
End class

Add the following key events handling code

Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) Handles txtID.KeyUp


If (Not Char.IsNumber(ChrW(e.KeyCode))) Then
MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
 In the above code for keyboard and mouse event, you can see, there are basically two
new things added:

o The event subroutine arguments sender and e


o The Handles clause
 The Handles clause allows the same subroutine to be used for all kinds of event calls like
mouse,key etc.
 The event handler arguments, sender and e, are the same for all event subroutines, in
part, so you can code an event subroutine that handles different types of events like the
example above.
 The sender argument provides information about the event that was raised. There's a
fairly small set of properties that sender provides directly.
 These properties carry just the basic information you need.
o Equals
GetHashCode
GetType
ReferenceEquals
ToString

 The sender arguement is often more useful if you instantiate an object using it. For
example, if you are processing a Button control:

o Dim myButton As Button = sender

 If you are processing a PictureBox control:

Dim myPicBox As PictureBox = sender


 Using these instances of controls, you can take advantage of the methods and properties
of the control. For example, you can get the Name of a control:

Dim myButton As Button = sender


Debug.WriteLine(myButton.Name)
or

Dim myTextBox As TextBox = sender


Debug.WriteLine(myTextBox.Name)
 The argument e carries whether it s a mouse arguments or keyboard arguments.

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

ADO.NET Object Model

The .Net Framework comprises of


1. Connection Oriented (or) Data Providers.
2. Disconnection Oriented (or) Datasets.

1. Connection Environment/ Data Providers:


In connected the application makes a connection to the Data source and then interacts with it
through SQL request using the same connection. In these cases the application stays connected to
DB system even when it is not using any Database operations.

2. Disconnected Oriented/ Datasets:


A datasets is an in – memory data store that can hold multiple tables at the same time. Datasets
can only hold data and do not interact with a data source.
DIRECT ACCESS (OR) .NET DATA PROVIDERS (OR) CONNETION
ENVIRONMENT
Data providers act as a bridge between an application and database. It is used to retrieve
data from a database and send back to the database after changes.

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

Sample C # Program for Connection Environment:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=CENTRE-I-62;Initial Catalog=management;Integrated
Security=True";
string query1 = "select * from employee";
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd1 = new SqlCommand(query1, cn);
SqlDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
Console.WriteLine(dr1[0] + " " + dr1[1] + " " + dr1[2] + " " + dr1[3] + " " + dr1[4]);
}
cn.Close();
Console.ReadLine();
} } }

INDIRECT ACCESS (OR) DATASETS (OR) DISCONNECTED ENVIRONMENT

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)
{

string connetionString = null;


SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
//int i = 0;
string sql = null;

connetionString = "Data Source=MIT-LAB2-SYS9;Initial Catalog=source;Persist


Security Info=True;User ID=sa;Password=mit123";
sql = "select source_id,source_name from source_table";

connection = new SqlConnection(connetionString);

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";

}
}
}

You might also like