Handling Exceptions and Stored Data - PowerPoint PPT Presentation

1 / 70
About This Presentation
Title:

Handling Exceptions and Stored Data

Description:

Learn about exceptions, including how they are thrown and caught ... While you browsed Web pages. While you were developing applications using C# ... – PowerPoint PPT presentation

Number of Views:68
Avg rating:3.0/5.0
Slides: 71
Provided by: manasi94
Category:

less

Transcript and Presenter's Notes

Title: Handling Exceptions and Stored Data


1
Chapter 11
  • Handling Exceptions and Stored Data

Microsoft Visual C .NET From Problem Analysis
to Program Design
2
Chapter Objectives
  • Learn about exceptions, including how they are
    thrown and caught
  • Become aware of and use exception-handling
    techniques to include trycatchfinally clauses
  • Explore the many exception classes and learn how
    to write and order multiple catch clauses
  • Instantiate objects of the file stream classes
    and use their members to create and process text
    files

3
Chapter Objectives (continued)
  • Be introduced to technologies used for accessing
    databases
  • Learn how to access and update databases using
    ADO.NET classes

4
Exceptions
  • Some circumstances are beyond programmers
    control
  • You have assumed nothing unusual would occur
  • Have probably experienced unhandled exceptions
    being thrown
  • While you browsed Web pages
  • While you were developing applications using C
  • Unless provisions are made for handling
    exceptions, your program may crash or produce
    erroneous results
  • Unhandled exception

5
Exceptions (continued)
Normally do not want to try to debug application
while it is running
Click No
6
Unhandled Exception
  • Message displayed when you are creating console
    application and unhandled exception occurs

7
Unhandled Exception (continued)
  • Selecting DebuggtStart to run application in
    Visual Studio
  • Yellow arrow marks the error (erroneous code
    highlighted)

8
Raising an Exception
  • Error encountered no recovery
  • Raise or throw an exception
  • Execution halts in the current method and the
    Common Language Runtime (CLR) attempts to locate
    an exception handler
  • Exception handlerblock of code to be executed
    when a certain type of error occurs
  • If no exception handler is found in current
    method, exception is thrown back to the calling
    method

9
Bugs, Errors, and Exceptions

  • Bugs differ from exceptions
  • Bugs, also called "programmer mistakes," should
    be caught and fixed before application released
  • Errorscan be created because of user actions
  • Example
  • Entering wrong type of data produces unhandled
    exception when ParseInt( ) called
  • Details button in Visual Studio lists a stack
    trace of methods with the method that raised the
    exception listed first

10
Bugs, Errors, and Exceptions (continued)
Stack trace
11
Exception-Handling Techniques
  • If event creates a problem frequently, best to
    use conditional expressions to catch and fix
    problem
  • Execution is slowed down when CLR has to halt a
    method and find an appropriate event handler
  • Exception-handling techniques are for serious
    errors that occur infrequently
  • Exceptions classes integrated within the FCL
  • Used with the trycatchfinally program
    constructs

12
TryCatchFinally Blocks
  • Code that may create a problem is placed in the
    try block
  • Code to deal with the problem (the exception
    handler) is placed in catch blocks
  • Catch clause
  • Code to be executed whether an exception is
    thrown or not is placed in the finally block

13
try // Statements catch
(ExceptionClassName exceptionIdentifier)
// Exception handler statements //
additional catch clauses finally //
Statements
Notice square brackets indicate optional entry
One catch clause required
finally clause optional
14
TryCatchFinally Blocks (continued)
  • Generic catch clause
  • Omit argument list with the catch
  • Any exception thrown is handled by executing code
    within that catch block
  • Control is never returned into the try block
    after an exception is thrown
  • Using a trycatch block can keep the program from
    terminating abnormally

15
Use of Generic Catch clause
Example 11-2Uses a generic catch block
16
What caused these exceptions to be thrown?
Never quite sure what causes the exception to be
thrown when a generic catch clause is used!
17
Exception Object
  • When an exception is raised, an object is created
  • Object has properties and behaviors (methods)
  • Catch clause may list an exception class
  • Catch without exception type does not give
    you access to an object
  • Base exception classException
  • Message property returns a string describing
    exception
  • StackTrace property returns a string that
    contains the called trace of methods

18
Exception Object (continued)
  • catch (System.Exception e)
  • Console.Error.WriteLine("Problem with
    scores - "
  • "Can not compute
    average")
  • Console.Error.WriteLine(e.Message)

19
Exception Classes
  • ApplicationException and SystemException classes
    form the basis for runtime exceptions

20
Exception Classes (continued)
  • ApplicationException
  • Derive from this class when you write your own
    exception class
  • User program must throw the exceptionnot the CLR
  • SystemException
  • Most runtime exceptions derive from this class
  • SystemException class adds no functionality to
    classes
  • Includes no additional properties or methods

21
SystemException Classes
Over 70 classes derive from the SystemException
class
22
System.DivideByZeroException
  • Derived class of System.ArithmeticException class
  • Thrown when an attempt to divide by zero occurs
  • Only thrown for integral or integer data types
  • Floating-point operands do not throw an exception
  • Result reported as either positive infinity,
    negative infinity, or Not-a-Number (NaN)
  • Follows the rules from IEEE 754 arithmetic

23
Filtering Multiple Exceptions
  • Can include multiple catch clauses
  • Enables writing code specific to thrown exception
  • Should be placed from most specific to the most
    generic
  • If Exception class is included, it should always
    be placed last

24
Custom Exceptions
  • Derive from the ApplicationException class

25
Custom Exceptions (continued)
  • Throwing a programmer-defined exception
  • Exception object is instantiated when "an
    exceptional condition occurs
  • Can be any condition, but should be one that
    happens infrequently
  • After object is instantiated, object is thrown

26
Throwing an Exception
  • static double GetResults(double value1, double
    value2)
  • if (value2 lt .0000001) // Careful comparing
    floating-point values
  • // for
    equality
  • FloatingPtDivisionException e new
  • FloatingPtDivisionException
  • ("Exception type Floating
    point division by zero")
  • throw e
  • return value1 / value2

27
Input Output (IO) Exceptions
  • System.IO.IOException
  • Direct descendent of Exception
  • Thrown when a specified file or directory is not
    found
  • Thrown when program attempts to read beyond the
    end of a file
  • Thrown when there are problems loading or
    accessing the contents of a file

28
Input Output (IO) Exceptions (continued)
29
File Streams
  • System.IO namespace
  • Several abstract classes for dealing with files
  • Stream, TextWriter, and TextReader
  • Stream classes provide generic methods for
    dealing with input/output
  • IO.Stream class and its subclassesbyte-level
    data
  • IO.TextWriter and IO.TextReaderdata in a text
    (readable) format
  • StreamReader and StreamWriter derived classes of
    IO.TextWriter and IO.TextReader

30
File Streams (continued)
31
File Streams (continued)
  • StreamWriter class for write data to text file
  • Includes implementations for Write( ) and
    WriteLine( )
  • StreamReader class to read or and from text files
  • Includes implementations of Read( ) and ReadLine(
    )
  • System.IO namespace
  • using System.IO

32
File Streams (continued)
  • StreamWriter outputFile new StreamWriter("someOu
    tputFileName")
  • StreamReader inputFile new StreamReader("someInp
    utFileName")
  • outputFile and inputFile represents the file
    stream objects
  • Actual file names are someOutputFileName and
    someInputFileNameinside double quotes
  • Place file extension such as .dat, .dta, or .txt
    onto the end of actual file name when it is
    created

33
File Streams (continued)
  • Use Write( ) or WriteLine( ) with the
    instantiated stream object
  • outputFile.WriteLine("This is the first line in a
    text file")
  • Use Read( ) or ReadLine( ) with the instantiated
    stream object
  • string inValue inputFile.ReadLine( )

34
File Streams (continued)
35
File Streams (continued)

36
File Streams (continued)
Static methods are called using class name
instead of object name
37
Writing Text Files
  • Enclosed attempts to access text files inside
    trycatch blocks
  • Constructor for StreamWriter class is overloaded
  • Can include Boolean variable indicating whether
    file should be appended to or overwritten if it
    already exists
  • New file is created by default
  • Values are placed in the file in a sequential
    fashion

38
Writing Text Files SayingGUI Application
39
Writing Text Files SayingGUI Application
(continued)
  • Three event-handler methods included
  • Form-load event handler, an object of the
    StreamWriter class is instantiated  
  • Included in a trycatch clause
  • Button click event-handler method retrieves the
    string from the text box and writes the text to
    the file
  • Also enclosed in a trycatch clause
  • Form closing event closes the file and releases
    resources associated with file
  • Also enclosed in a trycatch clause

40
Writing Text Files SayingGUI Application
(continued)
41
Writing Text Files SayingGUI Application
(continued)
If a path is not specified for the file name, the
bin\debug subdirectory for the current project is
used
42
Reading Text Files
  • StreamReader class enables lines of text to be
    read from a file
  • Constructor for StreamReader is overloaded
  • Can specify different encoding schema or an
    initial buffer size
  • Can use members of parent or ancestor classes or
    static members of the File class
  • To avoid programming catch for FileNotFoundExcepti
    on or DirectoryNotFoundException, call
    File.Exists(filename)

43
Reading Text FilesFileAccessApp Application
  • Read from text files in sequential fashion

44
Reading Text FilesFileAccessApp Application
(continued)
45
Database Access
  • Example DBMS include SQL server, Oracle, and
    Access
  • Many DBMSs store data in tabular format
  • Data in tables are related through common data
    field keys
  • Typically use a query language to program
    database access
  • Structured query language (SQL)
  • ActiveX Data Objects (ADO.NET).NET data access
    technology for accessing data in databases

46
ADO.NET
  • Includes number of classes that can be used to
    retrieve, manipulate, and update data in
    databases
  • Can work with databases in a disconnect manner
  • Database table(s) can be retrieved to a temporary
    file
  • To retrieve data first you must connect to the
    database
  • ADO.NET uses a feature called data providers to
    connect, execute commands, and retrieve results
    from a database

47
Data Providers
  • Microsoft SQL Server
  • Applications using SQL Server 7.0 or later
  • Oracle
  • Applications using Oracle data sources
  • Object Linking and Embedding Database (OLE DB)
  • Applications that use Microsoft Access databases
  • Open Database Connectivity (ODBC)
  • Applications supported by earlier versions of
    Visual Studio

48
Data Providers (continued)
  • Classes is encapsulated into a different
    namespace by provider
  • Four core classes make up each data provider
    namespace
  • ConnectionEstablishes a connection to a data
    source
  • CommandExecutes a command against a data source
  • DataReaderPerforms a forward-only (sequential)
    access of the data in the data source
  • DataAdapterPopulates a dataset and updates the
    database

49
Connecting to the Database (Microsoft Access DBMS)
  • Add using directive
  • using System.Data.OleDb
  • Instantiate an object of connection class
  • Send connection string that includes the actual
    database provider and the data source (name of
    the database)
  • string sConnection
  • sConnection "ProviderMicrosoft.Jet.OLEDB.4.0"
  • "Data Sourcemember.mdb"
  • OleDbConnection dbConn
  • dbConn new OleDbConnection(sConnection)
  • dbConn.Open()

Enclose in try catch block
50
Retrieving Data from the Database
  • One way to retrieve records programmaticallyissue
    an SQL query
  • Object of OleDbCommand class used to hold SQL
  • string sql
  • sql "Select From memberTable Order By
    LastName Asc, "
  • "FirstName Asc" // Note the
    two semicolons
  • OleDbCommand dbCmd new OleDbCommand()
  • dbCmd.CommandText sql // set command SQL
    string
  • dbCmd.Connection dbConn // dbConn is
    connection object

51
SQL Queries
  • Select From memberTable Order By LastName Asc,
    FirstName Asc
  • Asterisk () selects all fields (columns) in
    database
  • Can replace by field name(s)
  • Asc(ascending) returns in ascending order by
    LastName duplicate last names ordered by first
    name
  • Retrieves all rows (records)
  • Where clause can be added
  • Select PhoneNumber From memberTable Where
    FirstName 'Gary' AND LastName 'Jones'

52
Retrieving Data from the Database
  • Select StudentID, FirstName, LastName,
    PhoneNumber From memberTable

53
Processing Data
  • Can retrieve one record at a time in memory
  • Process that record before retrieving another
  • OR can store the entire result of the query in
    temporary data structure similar to an array
  • Disconnect from the database
  • ADO.NET includes data reader classes (by
    provider)
  • Used to read rows of data from a database

54
Retrieving Data Using a Data Reader
  • OleDbDataReader class
  • READ-ONLY access
  • Forward retrieval (sequential access)
  • Results returned as query executes
  • Sequentially loop through the query results
  • Only one row is stored in memory at a time
  • Useful to accessing data from large database
    tables
  • Declare an object of the OleDbDataReader class
  • Call ExecuteReader( ) method

55
Retrieving Data Using a Data Reader (continued)
  • To position the OleDbDataReader object onto the
    row of the first retrieved query result, use
    Read( ) method of the OleDbDataReader class
  • Read( ) also used to advance to the next record
  • Think about what is retrieved as one-dimensional
    table consisting of the fields from that one row
  • Fields can be referenced using actual ordinal
    index
  • Fields can also be referenced using the table's
    field names as indexers to the data reader object

56
Retrieving Data Using a Data Reader (continued)
  • First call to dbReader.Read( ) retrieves first
    row
  • dbReader0 refers to 1234
  • dbReader1 refers to Rebecca
  • dbReader"FirstName" also refers to "Rebecca"

Field name must be enclosed in double quotes when
used as indexers
57
Retrieving Data Using a Data Reader (continued)
  • Member aMember
  • OleDbDataReader dbReader
  • dbReader dbCmd.ExecuteReader( ) //
    dbCmdOleDbCommand object
  • while (dbReader.Read( ))
  • // retrieve records 1-by-1...
  • aMember new Member(dbReader"FirstName".To
    String( ),
  • dbReader"LastName".ToString( ))
  • this.listBox1.Items.Add(aMember)
  • dbReader.Close() // Close the Reader object
  • dbConn.Close() // Close the Connection object

58
Retrieving Data Using a Data Reader (continued)
59
Retrieving Data Using a Data Reader (continued)
60
Retrieving Data Using a Data Reader DBExample
Application
61
Updating Database Data
  • Data Reader enables read-only access to database
  • Several ways to change or update database
  • Can write Insert, Delete, and Update SQL
    statements and then execute those queries by
    calling OleDbCommand.ExecuteNonQuery( ) method
  • Can instantiate objects of dataset and data
    adapter classes
  • Use data adapter object to populate dataset
    object
  • Adapter class has Fill( ) and Update( ) methods

62
Updating Database Data (continued)
  • Not required to keep a continuous live connection
  • Can create temporary copy in memory of the
    records retrieved using a dataset
  • Interaction between dataset and actual database
    is controlled through data adapter
  • Each of the different data providers has its own
    dataset and data adapter objects
  • System.Data.OleDbAccess database

63
Using Datasets to Process Database Records
  • Instantiate a connection object using connection
    string
  • Not necessary to call Open( ) method
  • Select records (and fields) from database by
    executing SQL Select
  • Instantiate object of Dataset class (for a table)
  • DataSet memberDS new DataSet()
  • Instantiate an object of DataAdapter class
  • OleDbDataAdapter memberDataAdap new
    OleDbDataAdapter( )

64
Command Builder Class
  • Class that automatically generates SQL for
    updates
  • Must set the SelectCommand property of the
    OleDbDataAdapter class
  • private OleDbCommandBuilder cBuilder
  • cBuilder new OleDbCommandBuilder(memberDataAdap)
  • memberDataAdap.SelectCommand dbCmd
  • CommandBuilder object only used for datasets that
    map to a single database table

See slide 53 dbCmd set the SQL Select
65
Filling the Dataset using the Data Adapter
  • After instantiating objects of data adapter,
    dataset, and command builder classes
  • Using data adapter Fill( ) method to specify name
    of table to use as the data source
  • memberDataAdap.Fill(memberDS, "memberTable")
  • To show contents of table, presentation user
    interface layer is needed
  • Grid control works well

66
Creating a DataGrid to Hold the Dataset
  • Place DataGrid control object on Windows Form
  • DataGrid object can be selected from ToolBox
  • Able to navigate around in data grid
  • Can make changes by editing current records
  • Can insert and delete new records
  • To tie DataGrid object to dataset,
    SetDataBinding( ) method is used
  • this.dataGrid1.SetDataBinding(memberDS,
    "memberTable")

67
Updating the Database
  • Load the database into a DataGrid object and make
    changes
  • Flush the changes back up to live database using
    the Update( ) method of DataAdapter class
  • memberDataAdap.Update(memberDS, "memberTable")

68
Updating the Database DataSetExample Application
69
Updating the Database DataSetExample Application
70
Chapter Summary
  • Exceptions
  • How to throw and caught exceptions
  • Exception-handling techniques
  • trycatchfinally clauses
  • Exception classes
  • Use multiple catch clauses
  • File stream classes for sequential access
  • ADO.NET classes to access database records
Write a Comment
User Comments (0)
About PowerShow.com