SlideShare a Scribd company logo
1 of 50
Exception Handling, Debugging and Testing
Windows Applications

Pre-assessment Questions
    1.   Which of the following is a valid specific culture:
         a.  fr
         b.  de
         c.  fr-France
         d.  fr-Fr

    2.   Which of the following involves writing code in such a way that it is culture
         and language neutral?
         a.   Globalization
         b.   Localization
         c.   Culture-specific formatting
         d.   Deployment




 ©NIIT             Enhancing and Distributing Applications     Lesson 1B / Slide 1 of 50
Exception Handling, Debugging and Testing
Windows Applications

Pre-assessment Questions (Contd.)
    1.   Which method is used to create an instance of the Encoding class?
         a.  Encoding.GetEncoding
         b.  Encoding.newEncoding
         c.  new
         d.  Encoding.generateEncoding

    2.   Which of the following properties must be set for conveying information
         about a control to the accessibility aids?
         a.  Name
         b.  AccessibleName
         c.  AccessibleIdentity
         d.  AidName




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 2 of 50
Exception Handling, Debugging and Testing
Windows Applications

Pre-assessment Questions (Contd.)
    1.   Which of the following is not a culture-specific class?
         a.  DateTimeFormatInfo
         b.  Calendar
         c.  NumberFormatInfo
         d.  LanguageInfo




 ©NIIT             Enhancing and Distributing Applications     Lesson 1B / Slide 3 of 50
Exception Handling, Debugging and Testing
Windows Applications

Solutions to Pre-assessment
Questions
    1.   d.   fr-Fr
    2.   a.   Globalization
    3.   a.   Encoding.GetEncoding
    4.   b.   AccessibleName
    5.   d.   LanguageInfo




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 4 of 50
Exception Handling, Debugging and Testing
Windows Applications

Objectives
    In this lesson, you will learn to:
         • Handle and raise exceptions
         • Develop test plans
         • Configure the debugging environment
         • Use the Break mode to debug an application
         • Use debugger windows to trace and debug an application
         • Implement custom trace listeners
         • Implement trace switches




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 5 of 50
Exception Handling, Debugging and Testing
Windows Applications

Exception Handling
    •    An exception is termed as an abnormal condition encountered by an
         application during execution.
    •    Exception handling is the process of providing an alternate path of execution
         when the application is unable to execute in the desired way.
    •    By handling exceptions, you can prevent an application from terminating
         abruptly when an error is encountered.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 6 of 50
Exception Handling, Debugging and Testing
Windows Applications

Overview of Exception Handling
    •    Exceptions may be handled by placing specific code in an application that gets
         executed when an exception is raised.
    •    The exception handling code prevents the program from terminating abruptly
         and allows you to take appropriate action.
    •    Exception handling may be used in any method that uses operators that may
         generate an exception, or that calls into or accesses other procedures that may
         generate an exception.
    •    If an exception occurs in a method that does not contain an exception handler,
         then the exception is propagated back to the calling method.
    •    If the calling method also has no exception handler, then the exception is
         propagated back to that called method.
    •    When an error occurs, an object is created automatically that stores
         information about the error.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 7 of 50
Exception Handling, Debugging and Testing
Windows Applications

Types of Errors
         •   There are three types of errors that can occur in an application:
               • Syntax Errors: A syntax error occurs when the compiler cannot
                 compile the code.
               • Run-time Errors: A run-time error occurs when an application
                 attempts to perform an operation that is not allowed.
               • Logical Errors: A logical error occurs when an application compiles
                 and runs properly but does not produce the expected results.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 8 of 50
Exception Handling, Debugging and Testing
Windows Applications

Types of Exception Handling
    •    Visual Basic .NET provides these two ways to handle exceptions:
          • Structured Exception Handling
          • Unstructured Exception Handling




 ©NIIT           Enhancing and Distributing Applications   Lesson 1B / Slide 9 of 50
Exception Handling, Debugging and Testing
Windows Applications

Structured Exception Handling
    •    All the exceptions are derived from the System.Exception class.
    •    The hierarchy of the exception classes is displayed in the given figure.

            System.Exception




                  System.ApplicationException



                  System.Windows.Forms.AxHost.InvalidActiveXStateException


                  System.Runtime.Remoting.MetadataServices.SUDSParserException



                  System.IO.IsolatedStorage.IsolatedStorageException



                  System.Runtime.Remoting.MetadataServices.SUDSGeneratorException


                  System.SystemException


 ©NIIT              Enhancing and Distributing Applications                         Lesson 1B / Slide 10 of 50
Exception Handling, Debugging and Testing
Windows Applications

Structured Exception
Handling(Contd.)
    •    The exception classes derived from the System.Exception class are
         discussed below:
          • System.ApplicationException— This exception is thrown by user
               created applications.
          • System.Windows.Forms.AxHost.InvalidActiveXStateException— This
               exception is thrown when the ActiveX control that is in an invalid state
               is called by an application.
          • System.Runtime.Remoting.MetadataServices.SUDSParserException—
               This exception is thrown when the parsing process of Web Services
               Description Language (WSDL) generates an error.
          • System.IO.IsolatedStorage.IsolatedStorageException— This exception
               is thrown when an error is generated in an isolated storage operation.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 11 of 50
Exception Handling, Debugging and Testing
Windows Applications

Structured Exception
Handling(Contd.)
    •    System.SystemException — This exception class acts as a base class for all
         the predefined system exceptions. Some of the classes derived from this
         class are given below:
          • System.IO.IOException
          • System.Data.DataException
          • Sytsem.Data.SqlClient.SqlException
          • System.IndexOutOfRangeException
          • System.NullReferenceException
    •    In structured exception handling, the application is divided into blocks of
         code.




 ©NIIT           Enhancing and Distributing Applications   Lesson 1B / Slide 12 of 50
Exception Handling, Debugging and Testing
Windows Applications

Structured Exception
Handling(Contd.)
    •    The structure of the Try…Catch…Finally statement is given below:
          Try
          ' This block includes the code that can raise an error.
          Catch (optional filters)
           'This block includes the code that runs if the code in
          'The Try block gives an error and the filter on the Catch
               'statement is true, if specified.
          '(Additional Catch blocks)
          Finally
          'This block includes the code that will always run just before
               the Try statement exits.
           End Try



 ©NIIT          Enhancing and Distributing Applications   Lesson 1B / Slide 13 of 50
Exception Handling, Debugging and Testing
Windows Applications

Unstructured Exception Handling
    •    In unstructured exception handling, an On Error statement is placed in a
         code block.
    •    The On Error statement handles any error that occurs in that code block.
    •    When an error occurs in a called procedure that does not have an On Error
         statement, the exception is passed back to the calling procedure and the
         error is handled by the calling procedure.
    •    The Exit Sub statement should be placed immediately before the error
         handler block.
    •    You can use the On Error Resume Next statement to specify that when an
         error occurs, the control should pass to the next line of code following the
         line in which the error occurred.
    •    You can use the On Error GoTo 0 statement in a procedure to disable any
         error handler.
    •    Unstructured exception handling is not recommended because it is difficult to
         maintain the code containing the On Error statement.


 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 14 of 50
Exception Handling, Debugging and Testing
Windows Applications

The Error Object
    •    When an error occurs in an application, an instance of the Error object is
         created and the information about the error, such as the error message and
         number, is stored in it.
    •    The properties of the Error object that are commonly used are:
         • Number — Contains the integer value of the error.
         • Description — Contains the error text.
         • Source — Contains the information about the object that generated the
              error.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 15 of 50
Exception Handling, Debugging and Testing
Windows Applications

User-defined Exceptions
    •    In addition to handling pre-defined exceptions, users can create their own
         exceptions.
    •    User-defined exception classes are derived from the ApplicationException
         class.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 16 of 50
Exception Handling, Debugging and Testing
Windows Applications

Raising Exceptions
    •    There are instances when you want to raise exceptions.
    •    Exceptions can be explicitly thrown in an application by using the Throw()
         method.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 17 of 50
Exception Handling, Debugging and Testing
Windows Applications

Debugging a Windows-based
Application
    •    When writing code for applications, errors may be introduced in programs,
         these errors are called bugs.
    •    The process of locating and fixing bugs in a program is called Debugging.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 18 of 50
Exception Handling, Debugging and Testing
Windows Applications

Overview of Debugging
    •    Visual Basic .NET provides a set of tools that allow you to trace and correct
         errors in your programs in the development environment itself.
    •    To assist you in debugging logical and run-time errors, Visual Basic.NET
         provides extensive debugging tools.
    •    Another method to access the debugging tools is from the Debug menu.
    •    By using the debugging tools, you can perform the following actions:
         • Start execution
         • Break execution
         • Step through execution
         • Stop execution




 ©NIIT             Enhancing and Distributing Applications   Lesson 1B / Slide 19 of 50
Exception Handling, Debugging and Testing
Windows Applications

Configuring the Debugging
Environment
    •    The Debug version is built for debugging and the Release version is built for
         the final release distribution.
    •    The Debug configuration of a program is compiled with full symbolic debug
         information and no optimization.
    •    Optimization complicates debugging as the relationship between the source
         code and the generated instructions is more complex.
    •    The Release configuration of a program is fully optimized and contains no
         symbolic debug information.
    •    You can switch between Release and Debug versions by choosing Debug (or
         Release) from the Solution Configurations list box on the Standard toolbar.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 20 of 50
Exception Handling, Debugging and Testing
Windows Applications

Using the Break Mode
         •   When debugging, an application can be in the run mode or in the break
             mode.
         •   In Visual Basic.NET, you can debug a code in the break mode.
         •   In this mode, Visual Basic provides the ability to execute the application
             step-by-step.
         •   The values of the variables and expressions can be evaluated in this
             mode.
         •   When an application is running, in order to switch to the break mode,
             you can execute any of the following actions at run time:
             • Press the Ctrl and Break keys together
             • Select the Break option from the Run menu
             • Click the Break button on the Debug toolbar




 ©NIIT           Enhancing and Distributing Applications    Lesson 1B / Slide 21 of 50
Exception Handling, Debugging and Testing
Windows Applications

Setting a Breakpoint
         •   A break point can be set on an executable line of code.
         •   To set a breakpoint, you need to identify the statement where the error
             starts.
         •   You can remove a breakpoint from a code by selecting Remove
             Breakpoint from the shortcut menu of the code line at which the
             breakpoint is set.




 ©NIIT           Enhancing and Distributing Applications   Lesson 1B / Slide 22 of 50
Exception Handling, Debugging and Testing
Windows Applications

Stepping Through an Application
    •    When you set a breakpoint in an application and start the application using
         the Start option, the application execution halts at the breakpoint and the
         execution enters the break mode.
    •    In the break mode, you can select any of the following Debug menu options
         for executing the code:
         • Step Into
         • Step Over
         • Step Out




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 23 of 50
Exception Handling, Debugging and Testing
Windows Applications

The Debugger Windows
    •    When an application runs or is in the break mode, you can use the following
         windows to trace and debug an application:
         • Call Stack window
         • Watch window
         • Output window
         • Locals window
         • Immediate window




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 24 of 50
Exception Handling, Debugging and Testing
Windows Applications

Call Stack Window
    •    When an application is in the break mode, you can find the sequence of the
         called procedures by using the Call Stack window.
    •    The Call Stack window displays the procedure names, the parameter types,
         and the parameter values.
    •    You can display the Call Stack window by selecting Windows from the Debug
         menu and then selecting the Call Stack option from the Windows submenu.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 25 of 50
Exception Handling, Debugging and Testing
Windows Applications

Watch Window
    •    Using the Watch window, you can change the values of variables or
         expressions in the break mode and observe how these different values affect
         your code.
    •    Each variable or expression that you observe in the Watch window is called a
         watch expression.
    •    Visual Basic. NET automatically monitors watch expressions.
    •    The Watch window can be displayed by selecting Windows from the Debug
         menu and then selecting Watch1 from the Watch submenu.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 26 of 50
Exception Handling, Debugging and Testing
Windows Applications

Output Window
    •    The Output window is useful in displaying debug messages, such as build
         errors and any user-defined messages during run time.
    •    The Output window is displayed by using the ViewOther WindowsOutput
         option.
    •    You can display debug messages during run time by using the methods of
         the Debug class.
    •    The Debug class is derived from System.Diagnostics namespace and contains
         methods that you can use to debug applications.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 27 of 50
Exception Handling, Debugging and Testing
Windows Applications

Locals Window
    •    The Locals window is a debugging tool that allows you to view the values
         present in the variables declared in the local procedures.
    •    To display the Locals window, select DebugWindowsLocals option when
         debugging in the break mode.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 28 of 50
Exception Handling, Debugging and Testing
Windows Applications

Immediate Window
    •    The Immediate window is a debugging tool to check the values present in
         the global and local variables.
    •    The Immediate window allows you to:
         • Set the value of a variable to observe the change in the result based on
              the value that is set.
         • Create or destroy objects.
    •    To start the Immediate window select DebugWindowsImmediate to open
         the Immediate window.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 29 of 50
Exception Handling, Debugging and Testing
Windows Applications




                   Demo
             Using Breakpoints




 ©NIIT     Enhancing and Distributing Applications   Lesson 1B / Slide 30 of 50
Exception Handling, Debugging and Testing
Windows Applications

Problem Statement
    •    An application has been created to display the product ID for a product that
         costs more than $3000.
    •    A Windows Form has been designed with a ListBox control named lbprodid.
    •    A data adapter named OleDbDAProduct has been created, and the Base_Cost
         and ProdID columns of the table Product have been retrieved.
    •    A dataset named DsProduct1 has been generated for the data adapter.
    •    The following code has been written for the Load event of the form to display
         the ProductID of the products with cost more than $3000 in the list box.
         Dim criteria As String
         Dim sort As String
         Dim dt As DataTable
         Dim result() As DataRow
              Dim ctr As Integer
         OleDbDAProduct.Fill(DsProduct1)
         dt = DsProduct1.Tables("Product")
         criteria = "Base_Cost > '3000'"
 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 31 of 50
Exception Handling, Debugging and Testing
Windows Applications

Problem Statement (Contd.)
    sort = "ProdID DESC"
    result = DsProduct1.Product.Select(criteria, sort)
    For ctr = 0 To (result.Length - 1)
    lbprodid.Items.Add(result(0)("ProdID").ToString)
    Next ctr


    •    However, the application does not give the expected output. The list box
         displays one product ID multiple times.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 32 of 50
Exception Handling, Debugging and Testing
Windows Applications

Solution
    •    To locate the error in the above program, the following steps need to be
         performed:
         1.   Identify the starting point to search for errors.
         2.   Set a breakpoint.
         3.   Run the application and trace the error.
         4.   Rectify the code.
         5.   Verify the output of the code.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 33 of 50
Exception Handling, Debugging and Testing
Windows Applications




                   Demo
         Debugging a Windows-based
                Application




 ©NIIT      Enhancing and Distributing Applications   Lesson 1B / Slide 34 of 50
Exception Handling, Debugging and Testing
Windows Applications

Problem Statement
    •    An application has been developed that displays the corresponding base cost
         and the product name of the product ID selected by the user from a list box.
    •      A data adapter named OleDbDAProduct has been created, and the
         Base_Cost and ProdID columns of the table Product have been retrieved.
    • A dataset named DSProduct has been generated for the data adapter.
    • A ListBox control named lbprodid, two TextBox controls, and a Button control
         with Text property set to Display have been added to the Form. The following
         general level declarations have been made.
    A ListBox control named lbprodid, two TextBox controls, and a Button control with
         Text property set to Display have been added to the Form. The following
         general level declarations have been made.
              Dim dt As DataTable
              Dim result(), resultarray As DataRow
              Dim prodid, criteria, sort As String
              Dim ctr As Integer


 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 35 of 50
Exception Handling, Debugging and Testing
Windows Applications

Problem Statement (Contd.)
    •   The following code has been added:
    Private Sub Form1_Load(ByVal sender As System.Object,                ByVal    e    As
        System.EventArgs) Handles MyBase.Load

    OleDbDAProduct.Fill(DSProduct)
    dt = DSProduct.Tables("Product")
    criteria = "Base_Cost > '3000'"
    sort = "ProdID DESC"
    result = DSProduct.Product.Select(criteria, sort)

    For ctr = 0 To (result.Length - 1)
    lbprodid.Items.Add(result(ctr)("ProdID").ToString)
    Next ctr

    End Sub

 ©NIIT          Enhancing and Distributing Applications   Lesson 1B / Slide 36 of 50
Exception Handling, Debugging and Testing
Windows Applications

Problem Statement (Contd.)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
        System.EventArgs) Handles Display.Click

    prodid = lbprodid.SelectedItem
    prodid = "P014"
    dt = DSProduct.Tables("Product")
    resultarray = dt.Rows.Find(prodid)
    TextBox1.Text = resultarray(1)
    TextBox2.Text = resultarray(2)
    End Sub
    • However, the application displays the product name and the base cost of the
        product ID P014 regardless of the ID selected by the user.




 ©NIIT           Enhancing and Distributing Applications   Lesson 1B / Slide 37 of 50
Exception Handling, Debugging and Testing
Windows Applications

Solution
    •    To solve the preceding problem, the following steps need to be performed:
         1.   Identify the mechanism to debug the code.
         2.   Implement debugging.
         3.   Rectify the code.
         4.   Verify the output of the code.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 38 of 50
Exception Handling, Debugging and Testing
Windows Applications

Testing a Windows-based Application
  •      Testing an application ensures that it fulfills the requirements for which it
         was designed and meets quality expectations.
  •      An application must be tested to ensure that it meets customer expectations.
  •      The compiler can detects only syntax errors, but the run-time errors and
         logical errors might not be exposed unless the application is thoroughly
         tested.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 39 of 50
Exception Handling, Debugging and Testing
Windows Applications

Overview of Testing
  •      Testing measures the quality of the software you are developing.
  •      Testing is undertaken to find and resolve the defects in your application.
  •      Testing can be of various types, which include:
         • Unit testing: Unit testing consists of isolating the smallest piece of
              testable software from the remaining application and determining
              whether it behaves as expected.
         • Integration testing: Integration testing combines two or more tested
              units into a component and tests the interface between them.
         • Regression testing: In regression testing you rerun the existing tests
              against the modified code to determine whether the changes have
              affected anything that was working correctly before the modification of
              code.
         • Acceptance testing: During acceptance testing, users are allowed to use
              the application and give feedback about the functionality, effectiveness,
              and efficiency of the application as per the requirements.


 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 40 of 50
Exception Handling, Debugging and Testing
Windows Applications

Developing a Test Plan
    •    Planning for a test includes budget, schedule, and performance
         considerations.
    •    Preparing a proper test plan makes the testing more effective and efficient.
    •    A test plan outlines the entire testing process and includes individual test
         cases.
    •    A test plan consists of the following components:
         • Test Scenario: The plan for testing each module in an application is
              called a test scenario.
         • Test Cases: Testing for every possible input value is almost an
              impossible task so testing can be done for some representative inputs,
              which are called test cases.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 41 of 50
Exception Handling, Debugging and Testing
Windows Applications

Implementing Tracing
    •    Tracing is a technique that allows you to log informative messages about an
         application’s conditions at run time.
    •    Using tracing, you can get informative messages about the execution of your
         application without interrupting the application execution even after it has
         been deployed.
    •    There are three phases of code tracing:
         • Instrumentation: In the instrumentation phase, trace code is added to
              your application.
         • Tracing: In the tracing phase, the tracing code writes information about
              the execution of the application to the specified target.
         • Analysis: In the analysis phase, tracing information is evaluated to
              identify and understand problems in the application.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 42 of 50
Exception Handling, Debugging and Testing
Windows Applications

Using the Debug and Trace Classes
    •    The System.Diagnostics namespace contains the Debug and Trace classes
         that include Shared methods which can be used to test conditions at run
         time and log the results.
    •    The Debug class is mainly used in the development phase for debugging.
    •    The Trace class is used for testing and optimization even after an application
         is compiled and released.
    •    The six Debug and Trace methods that write tracing information are listed
         below:
         • Assert
         • Fail
         • Write
         • WriteLine
         • WriteIf
         • WriteLineIf

 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 43 of 50
Exception Handling, Debugging and Testing
Windows Applications

Working with Listeners
    •    The Listeners collection includes classes that can receive output from the
         Shared methods of the Trace and Debug classes.
    •    Each member of the Listeners collection collects, stores, and routes tracing
         messages.
    •    There are three types of predefined listeners:
         • DefaultTraceListener: It is an instance of the DefaultTraceListener class
              and is a default member of the Listeners collection.
         • TextWriterTraceListener: It is an instance of the
              TextWriterTraceListener class and it redirects trace output to an
              instance of the TextWriter class or to a Stream object.
         • EventLogTraceListener: It is an instance of the EventLogTraceListener
              class and it redirects trace output to an event log.




 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 44 of 50
Exception Handling, Debugging and Testing
Windows Applications

Logging Trace Output to Text Files
    •    The TextWriterTraceListener class is used to log trace output to text files.
    •    To log trace output to a text file, the following steps must be performed:
         1.   Create an instance of a FileStream object that specifies the appropriate
              text file.
                    Dim myFile As New System.IO.FileStream _
                    (“C:myFile.txt”, IO.FileMode.OpenOrCreate)
         4.   Create an instance of TextWriterTraceListener that specifies the new
              FileStream object as its target.
                    Dim myListener As New TextWriterTraceListener(myFile)
         6.   Add the new listener to the Trace.Listeners collection.
                    Trace.Listeners.Add(myListener)
              flush the Trace buffer by calling the Flush method to write output to the
              text file.
                    Trace.Flush()


 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 45 of 50
Exception Handling, Debugging and Testing
Windows Applications

Logging Trace Output to an EventLog
    •    You use the EventLogTraceListener class to log the trace output to an
         EventLog object.
    •    To log the trace output to an EventLog, the following steps must be
         performed:
         1.   Create an instance of a EventLog object and assign it to a new event
              log or an existing event log.
                    Dim myLog As New EventLog (“Event Log”)
         2.   Set the Source property of the EventLog.
                    myLog.Source = “Trace Output”
         3.   Create an instance of EventLogTraceListener that specifies the new log
              as its target.
                    Dim myListener As New EventLogTraceListener(myLog)
         4.   Add the new listener to the Trace.Listeners collection.
                    Trace.Listeners.Add(myListener)


 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 46 of 50
Exception Handling, Debugging and Testing
Windows Applications

Implementing Trace Switches
    •    Trace switches allow you to enable, disable, and filter tracing output.
    •    Two types of trace switches are provided in the .NET Framework:
         • BooleanSwitch Class: The BooleanSwitch class acts as a toggle switch
              that may either enable or disable a variety of trace statements.
         • TraceSwitch Class: The TraceSwitch class allows you to enable a trace
              switch for a particular tracing level.
    •    To use the BooleanSwitch or the TraceSwitch class you need to create an
         instance of these classes.
    •    The TraceSwitch class exposes four read-only properties that represent the
         Trace levels. These are:
         • TraceSwitch.TraceError Property
         • TraceSwitch.TraceWarning Property
         • TraceSwitch.TraceInfo Property
         • TraceSwitch.TraceVerbose Property

 ©NIIT            Enhancing and Distributing Applications   Lesson 1B / Slide 47 of 50
Exception Handling, Debugging and Testing
Windows Applications

Summary
    In this lesson, you learned that:


         •   The types of errors that can occur in an application are syntax errors, run-
             time errors, and logical errors.
         •   An exception is an abnormal condition that an application encounters
             during execution.
         •   Exception handling is the process of providing an alternate path to be
             executed when the application is not able to execute in the desired way.
         •   Visual Basic .NET provides two methods to handle exceptions:
                • Structured exception handling
                • Unstructured exception handling
         •   In addition to handling pre-defined exceptions, users can create their own
             exceptions by deriving an exception class from the ApplicationException
             class.


 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 48 of 50
Exception Handling, Debugging and Testing
Windows Applications

Summary (Contd.)
         •   Once an application has been coded, it must be tested to ensure that it
             fulfills the requirements for which it was designed and meets quality
             expectations.
         •   There are various types of testing that an application has to go through.
             These include unit testing, integration testing, regression testing and
             acceptance testing.
         •   For testing to be successful, a test plan must be created that outlines the
             entire process of testing and includes budget, schedule and performance
             considerations.
         •   In order to assist you in debugging logical and runtime errors, Visual Basic
             .NET provides extensive debugging tools. You can use the Visual Basic
             .NET Debug toolbar to access these tools.
         •   By using the debugging tools, you can perform the following actions:
                • Start execution
                • Step through execution
                • Stop execution
 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 49 of 50
Exception Handling, Debugging and Testing
Windows Applications

Summary (Contd.)
         •   You can log informative messages about your application’s conditions at
             run time by using tracing.
         •   Tracing can be implemented by using the Trace and Debug classes.
         •   The Listeners collection is a group of classes capable of receiving output
             from the Debug and Trace classes.
         •   Trace switches allow you to enable, disable, and filter tracing output.
         •   Conditional compilation is a means of selectively compiling portions of
             your program code. This can be used for creating multiple versions of your
             application without the need to maintain multiple copies of code.




 ©NIIT              Enhancing and Distributing Applications   Lesson 1B / Slide 50 of 50

More Related Content

Viewers also liked (14)

Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
Decisions
DecisionsDecisions
Decisions
 
Simple debugging
Simple debuggingSimple debugging
Simple debugging
 
Data types vbnet
Data types vbnetData types vbnet
Data types vbnet
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
Active x control
Active x controlActive x control
Active x control
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
Exception handling
Exception handlingException handling
Exception handling
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
PPT on break even analysis
PPT on break even analysisPPT on break even analysis
PPT on break even analysis
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 

Similar to Vb.net session 12

Dr.Jonathan Software verification validation.ppt
Dr.Jonathan Software verification validation.pptDr.Jonathan Software verification validation.ppt
Dr.Jonathan Software verification validation.ppt
Phial
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Alpesh Oza
 
Vb.net session 13
Vb.net session 13Vb.net session 13
Vb.net session 13
Niit Care
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
Sujit Kumar
 

Similar to Vb.net session 12 (20)

Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
TDD - Unit Testing
TDD - Unit TestingTDD - Unit Testing
TDD - Unit Testing
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
Dr.Jonathan Software verification validation.ppt
Dr.Jonathan Software verification validation.pptDr.Jonathan Software verification validation.ppt
Dr.Jonathan Software verification validation.ppt
 
Dacj 2-1 b
Dacj 2-1 bDacj 2-1 b
Dacj 2-1 b
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Introduction to Software Testing
Introduction to Software TestingIntroduction to Software Testing
Introduction to Software Testing
 
Vb.net session 13
Vb.net session 13Vb.net session 13
Vb.net session 13
 
Exception handling
Exception handlingException handling
Exception handling
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Post-mortem Debugging of Windows Applications
Post-mortem Debugging of  Windows ApplicationsPost-mortem Debugging of  Windows Applications
Post-mortem Debugging of Windows Applications
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptx
 
Certification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptxCertification preparation - Error Handling and Troubleshooting recap.pptx
Certification preparation - Error Handling and Troubleshooting recap.pptx
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 

More from Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Vb.net session 12

  • 1. Exception Handling, Debugging and Testing Windows Applications Pre-assessment Questions 1. Which of the following is a valid specific culture: a. fr b. de c. fr-France d. fr-Fr 2. Which of the following involves writing code in such a way that it is culture and language neutral? a. Globalization b. Localization c. Culture-specific formatting d. Deployment ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 1 of 50
  • 2. Exception Handling, Debugging and Testing Windows Applications Pre-assessment Questions (Contd.) 1. Which method is used to create an instance of the Encoding class? a. Encoding.GetEncoding b. Encoding.newEncoding c. new d. Encoding.generateEncoding 2. Which of the following properties must be set for conveying information about a control to the accessibility aids? a. Name b. AccessibleName c. AccessibleIdentity d. AidName ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 2 of 50
  • 3. Exception Handling, Debugging and Testing Windows Applications Pre-assessment Questions (Contd.) 1. Which of the following is not a culture-specific class? a. DateTimeFormatInfo b. Calendar c. NumberFormatInfo d. LanguageInfo ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 3 of 50
  • 4. Exception Handling, Debugging and Testing Windows Applications Solutions to Pre-assessment Questions 1. d. fr-Fr 2. a. Globalization 3. a. Encoding.GetEncoding 4. b. AccessibleName 5. d. LanguageInfo ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 4 of 50
  • 5. Exception Handling, Debugging and Testing Windows Applications Objectives In this lesson, you will learn to: • Handle and raise exceptions • Develop test plans • Configure the debugging environment • Use the Break mode to debug an application • Use debugger windows to trace and debug an application • Implement custom trace listeners • Implement trace switches ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 5 of 50
  • 6. Exception Handling, Debugging and Testing Windows Applications Exception Handling • An exception is termed as an abnormal condition encountered by an application during execution. • Exception handling is the process of providing an alternate path of execution when the application is unable to execute in the desired way. • By handling exceptions, you can prevent an application from terminating abruptly when an error is encountered. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 6 of 50
  • 7. Exception Handling, Debugging and Testing Windows Applications Overview of Exception Handling • Exceptions may be handled by placing specific code in an application that gets executed when an exception is raised. • The exception handling code prevents the program from terminating abruptly and allows you to take appropriate action. • Exception handling may be used in any method that uses operators that may generate an exception, or that calls into or accesses other procedures that may generate an exception. • If an exception occurs in a method that does not contain an exception handler, then the exception is propagated back to the calling method. • If the calling method also has no exception handler, then the exception is propagated back to that called method. • When an error occurs, an object is created automatically that stores information about the error. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 7 of 50
  • 8. Exception Handling, Debugging and Testing Windows Applications Types of Errors • There are three types of errors that can occur in an application: • Syntax Errors: A syntax error occurs when the compiler cannot compile the code. • Run-time Errors: A run-time error occurs when an application attempts to perform an operation that is not allowed. • Logical Errors: A logical error occurs when an application compiles and runs properly but does not produce the expected results. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 8 of 50
  • 9. Exception Handling, Debugging and Testing Windows Applications Types of Exception Handling • Visual Basic .NET provides these two ways to handle exceptions: • Structured Exception Handling • Unstructured Exception Handling ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 9 of 50
  • 10. Exception Handling, Debugging and Testing Windows Applications Structured Exception Handling • All the exceptions are derived from the System.Exception class. • The hierarchy of the exception classes is displayed in the given figure. System.Exception System.ApplicationException System.Windows.Forms.AxHost.InvalidActiveXStateException System.Runtime.Remoting.MetadataServices.SUDSParserException System.IO.IsolatedStorage.IsolatedStorageException System.Runtime.Remoting.MetadataServices.SUDSGeneratorException System.SystemException ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 10 of 50
  • 11. Exception Handling, Debugging and Testing Windows Applications Structured Exception Handling(Contd.) • The exception classes derived from the System.Exception class are discussed below: • System.ApplicationException— This exception is thrown by user created applications. • System.Windows.Forms.AxHost.InvalidActiveXStateException— This exception is thrown when the ActiveX control that is in an invalid state is called by an application. • System.Runtime.Remoting.MetadataServices.SUDSParserException— This exception is thrown when the parsing process of Web Services Description Language (WSDL) generates an error. • System.IO.IsolatedStorage.IsolatedStorageException— This exception is thrown when an error is generated in an isolated storage operation. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 11 of 50
  • 12. Exception Handling, Debugging and Testing Windows Applications Structured Exception Handling(Contd.) • System.SystemException — This exception class acts as a base class for all the predefined system exceptions. Some of the classes derived from this class are given below: • System.IO.IOException • System.Data.DataException • Sytsem.Data.SqlClient.SqlException • System.IndexOutOfRangeException • System.NullReferenceException • In structured exception handling, the application is divided into blocks of code. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 12 of 50
  • 13. Exception Handling, Debugging and Testing Windows Applications Structured Exception Handling(Contd.) • The structure of the Try…Catch…Finally statement is given below: Try ' This block includes the code that can raise an error. Catch (optional filters) 'This block includes the code that runs if the code in 'The Try block gives an error and the filter on the Catch 'statement is true, if specified. '(Additional Catch blocks) Finally 'This block includes the code that will always run just before the Try statement exits. End Try ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 13 of 50
  • 14. Exception Handling, Debugging and Testing Windows Applications Unstructured Exception Handling • In unstructured exception handling, an On Error statement is placed in a code block. • The On Error statement handles any error that occurs in that code block. • When an error occurs in a called procedure that does not have an On Error statement, the exception is passed back to the calling procedure and the error is handled by the calling procedure. • The Exit Sub statement should be placed immediately before the error handler block. • You can use the On Error Resume Next statement to specify that when an error occurs, the control should pass to the next line of code following the line in which the error occurred. • You can use the On Error GoTo 0 statement in a procedure to disable any error handler. • Unstructured exception handling is not recommended because it is difficult to maintain the code containing the On Error statement. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 14 of 50
  • 15. Exception Handling, Debugging and Testing Windows Applications The Error Object • When an error occurs in an application, an instance of the Error object is created and the information about the error, such as the error message and number, is stored in it. • The properties of the Error object that are commonly used are: • Number — Contains the integer value of the error. • Description — Contains the error text. • Source — Contains the information about the object that generated the error. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 15 of 50
  • 16. Exception Handling, Debugging and Testing Windows Applications User-defined Exceptions • In addition to handling pre-defined exceptions, users can create their own exceptions. • User-defined exception classes are derived from the ApplicationException class. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 16 of 50
  • 17. Exception Handling, Debugging and Testing Windows Applications Raising Exceptions • There are instances when you want to raise exceptions. • Exceptions can be explicitly thrown in an application by using the Throw() method. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 17 of 50
  • 18. Exception Handling, Debugging and Testing Windows Applications Debugging a Windows-based Application • When writing code for applications, errors may be introduced in programs, these errors are called bugs. • The process of locating and fixing bugs in a program is called Debugging. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 18 of 50
  • 19. Exception Handling, Debugging and Testing Windows Applications Overview of Debugging • Visual Basic .NET provides a set of tools that allow you to trace and correct errors in your programs in the development environment itself. • To assist you in debugging logical and run-time errors, Visual Basic.NET provides extensive debugging tools. • Another method to access the debugging tools is from the Debug menu. • By using the debugging tools, you can perform the following actions: • Start execution • Break execution • Step through execution • Stop execution ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 19 of 50
  • 20. Exception Handling, Debugging and Testing Windows Applications Configuring the Debugging Environment • The Debug version is built for debugging and the Release version is built for the final release distribution. • The Debug configuration of a program is compiled with full symbolic debug information and no optimization. • Optimization complicates debugging as the relationship between the source code and the generated instructions is more complex. • The Release configuration of a program is fully optimized and contains no symbolic debug information. • You can switch between Release and Debug versions by choosing Debug (or Release) from the Solution Configurations list box on the Standard toolbar. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 20 of 50
  • 21. Exception Handling, Debugging and Testing Windows Applications Using the Break Mode • When debugging, an application can be in the run mode or in the break mode. • In Visual Basic.NET, you can debug a code in the break mode. • In this mode, Visual Basic provides the ability to execute the application step-by-step. • The values of the variables and expressions can be evaluated in this mode. • When an application is running, in order to switch to the break mode, you can execute any of the following actions at run time: • Press the Ctrl and Break keys together • Select the Break option from the Run menu • Click the Break button on the Debug toolbar ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 21 of 50
  • 22. Exception Handling, Debugging and Testing Windows Applications Setting a Breakpoint • A break point can be set on an executable line of code. • To set a breakpoint, you need to identify the statement where the error starts. • You can remove a breakpoint from a code by selecting Remove Breakpoint from the shortcut menu of the code line at which the breakpoint is set. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 22 of 50
  • 23. Exception Handling, Debugging and Testing Windows Applications Stepping Through an Application • When you set a breakpoint in an application and start the application using the Start option, the application execution halts at the breakpoint and the execution enters the break mode. • In the break mode, you can select any of the following Debug menu options for executing the code: • Step Into • Step Over • Step Out ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 23 of 50
  • 24. Exception Handling, Debugging and Testing Windows Applications The Debugger Windows • When an application runs or is in the break mode, you can use the following windows to trace and debug an application: • Call Stack window • Watch window • Output window • Locals window • Immediate window ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 24 of 50
  • 25. Exception Handling, Debugging and Testing Windows Applications Call Stack Window • When an application is in the break mode, you can find the sequence of the called procedures by using the Call Stack window. • The Call Stack window displays the procedure names, the parameter types, and the parameter values. • You can display the Call Stack window by selecting Windows from the Debug menu and then selecting the Call Stack option from the Windows submenu. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 25 of 50
  • 26. Exception Handling, Debugging and Testing Windows Applications Watch Window • Using the Watch window, you can change the values of variables or expressions in the break mode and observe how these different values affect your code. • Each variable or expression that you observe in the Watch window is called a watch expression. • Visual Basic. NET automatically monitors watch expressions. • The Watch window can be displayed by selecting Windows from the Debug menu and then selecting Watch1 from the Watch submenu. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 26 of 50
  • 27. Exception Handling, Debugging and Testing Windows Applications Output Window • The Output window is useful in displaying debug messages, such as build errors and any user-defined messages during run time. • The Output window is displayed by using the ViewOther WindowsOutput option. • You can display debug messages during run time by using the methods of the Debug class. • The Debug class is derived from System.Diagnostics namespace and contains methods that you can use to debug applications. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 27 of 50
  • 28. Exception Handling, Debugging and Testing Windows Applications Locals Window • The Locals window is a debugging tool that allows you to view the values present in the variables declared in the local procedures. • To display the Locals window, select DebugWindowsLocals option when debugging in the break mode. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 28 of 50
  • 29. Exception Handling, Debugging and Testing Windows Applications Immediate Window • The Immediate window is a debugging tool to check the values present in the global and local variables. • The Immediate window allows you to: • Set the value of a variable to observe the change in the result based on the value that is set. • Create or destroy objects. • To start the Immediate window select DebugWindowsImmediate to open the Immediate window. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 29 of 50
  • 30. Exception Handling, Debugging and Testing Windows Applications Demo Using Breakpoints ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 30 of 50
  • 31. Exception Handling, Debugging and Testing Windows Applications Problem Statement • An application has been created to display the product ID for a product that costs more than $3000. • A Windows Form has been designed with a ListBox control named lbprodid. • A data adapter named OleDbDAProduct has been created, and the Base_Cost and ProdID columns of the table Product have been retrieved. • A dataset named DsProduct1 has been generated for the data adapter. • The following code has been written for the Load event of the form to display the ProductID of the products with cost more than $3000 in the list box. Dim criteria As String Dim sort As String Dim dt As DataTable Dim result() As DataRow Dim ctr As Integer OleDbDAProduct.Fill(DsProduct1) dt = DsProduct1.Tables("Product") criteria = "Base_Cost > '3000'" ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 31 of 50
  • 32. Exception Handling, Debugging and Testing Windows Applications Problem Statement (Contd.) sort = "ProdID DESC" result = DsProduct1.Product.Select(criteria, sort) For ctr = 0 To (result.Length - 1) lbprodid.Items.Add(result(0)("ProdID").ToString) Next ctr • However, the application does not give the expected output. The list box displays one product ID multiple times. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 32 of 50
  • 33. Exception Handling, Debugging and Testing Windows Applications Solution • To locate the error in the above program, the following steps need to be performed: 1. Identify the starting point to search for errors. 2. Set a breakpoint. 3. Run the application and trace the error. 4. Rectify the code. 5. Verify the output of the code. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 33 of 50
  • 34. Exception Handling, Debugging and Testing Windows Applications Demo Debugging a Windows-based Application ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 34 of 50
  • 35. Exception Handling, Debugging and Testing Windows Applications Problem Statement • An application has been developed that displays the corresponding base cost and the product name of the product ID selected by the user from a list box. • A data adapter named OleDbDAProduct has been created, and the Base_Cost and ProdID columns of the table Product have been retrieved. • A dataset named DSProduct has been generated for the data adapter. • A ListBox control named lbprodid, two TextBox controls, and a Button control with Text property set to Display have been added to the Form. The following general level declarations have been made. A ListBox control named lbprodid, two TextBox controls, and a Button control with Text property set to Display have been added to the Form. The following general level declarations have been made. Dim dt As DataTable Dim result(), resultarray As DataRow Dim prodid, criteria, sort As String Dim ctr As Integer ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 35 of 50
  • 36. Exception Handling, Debugging and Testing Windows Applications Problem Statement (Contd.) • The following code has been added: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load OleDbDAProduct.Fill(DSProduct) dt = DSProduct.Tables("Product") criteria = "Base_Cost > '3000'" sort = "ProdID DESC" result = DSProduct.Product.Select(criteria, sort) For ctr = 0 To (result.Length - 1) lbprodid.Items.Add(result(ctr)("ProdID").ToString) Next ctr End Sub ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 36 of 50
  • 37. Exception Handling, Debugging and Testing Windows Applications Problem Statement (Contd.) Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Display.Click prodid = lbprodid.SelectedItem prodid = "P014" dt = DSProduct.Tables("Product") resultarray = dt.Rows.Find(prodid) TextBox1.Text = resultarray(1) TextBox2.Text = resultarray(2) End Sub • However, the application displays the product name and the base cost of the product ID P014 regardless of the ID selected by the user. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 37 of 50
  • 38. Exception Handling, Debugging and Testing Windows Applications Solution • To solve the preceding problem, the following steps need to be performed: 1. Identify the mechanism to debug the code. 2. Implement debugging. 3. Rectify the code. 4. Verify the output of the code. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 38 of 50
  • 39. Exception Handling, Debugging and Testing Windows Applications Testing a Windows-based Application • Testing an application ensures that it fulfills the requirements for which it was designed and meets quality expectations. • An application must be tested to ensure that it meets customer expectations. • The compiler can detects only syntax errors, but the run-time errors and logical errors might not be exposed unless the application is thoroughly tested. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 39 of 50
  • 40. Exception Handling, Debugging and Testing Windows Applications Overview of Testing • Testing measures the quality of the software you are developing. • Testing is undertaken to find and resolve the defects in your application. • Testing can be of various types, which include: • Unit testing: Unit testing consists of isolating the smallest piece of testable software from the remaining application and determining whether it behaves as expected. • Integration testing: Integration testing combines two or more tested units into a component and tests the interface between them. • Regression testing: In regression testing you rerun the existing tests against the modified code to determine whether the changes have affected anything that was working correctly before the modification of code. • Acceptance testing: During acceptance testing, users are allowed to use the application and give feedback about the functionality, effectiveness, and efficiency of the application as per the requirements. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 40 of 50
  • 41. Exception Handling, Debugging and Testing Windows Applications Developing a Test Plan • Planning for a test includes budget, schedule, and performance considerations. • Preparing a proper test plan makes the testing more effective and efficient. • A test plan outlines the entire testing process and includes individual test cases. • A test plan consists of the following components: • Test Scenario: The plan for testing each module in an application is called a test scenario. • Test Cases: Testing for every possible input value is almost an impossible task so testing can be done for some representative inputs, which are called test cases. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 41 of 50
  • 42. Exception Handling, Debugging and Testing Windows Applications Implementing Tracing • Tracing is a technique that allows you to log informative messages about an application’s conditions at run time. • Using tracing, you can get informative messages about the execution of your application without interrupting the application execution even after it has been deployed. • There are three phases of code tracing: • Instrumentation: In the instrumentation phase, trace code is added to your application. • Tracing: In the tracing phase, the tracing code writes information about the execution of the application to the specified target. • Analysis: In the analysis phase, tracing information is evaluated to identify and understand problems in the application. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 42 of 50
  • 43. Exception Handling, Debugging and Testing Windows Applications Using the Debug and Trace Classes • The System.Diagnostics namespace contains the Debug and Trace classes that include Shared methods which can be used to test conditions at run time and log the results. • The Debug class is mainly used in the development phase for debugging. • The Trace class is used for testing and optimization even after an application is compiled and released. • The six Debug and Trace methods that write tracing information are listed below: • Assert • Fail • Write • WriteLine • WriteIf • WriteLineIf ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 43 of 50
  • 44. Exception Handling, Debugging and Testing Windows Applications Working with Listeners • The Listeners collection includes classes that can receive output from the Shared methods of the Trace and Debug classes. • Each member of the Listeners collection collects, stores, and routes tracing messages. • There are three types of predefined listeners: • DefaultTraceListener: It is an instance of the DefaultTraceListener class and is a default member of the Listeners collection. • TextWriterTraceListener: It is an instance of the TextWriterTraceListener class and it redirects trace output to an instance of the TextWriter class or to a Stream object. • EventLogTraceListener: It is an instance of the EventLogTraceListener class and it redirects trace output to an event log. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 44 of 50
  • 45. Exception Handling, Debugging and Testing Windows Applications Logging Trace Output to Text Files • The TextWriterTraceListener class is used to log trace output to text files. • To log trace output to a text file, the following steps must be performed: 1. Create an instance of a FileStream object that specifies the appropriate text file. Dim myFile As New System.IO.FileStream _ (“C:myFile.txt”, IO.FileMode.OpenOrCreate) 4. Create an instance of TextWriterTraceListener that specifies the new FileStream object as its target. Dim myListener As New TextWriterTraceListener(myFile) 6. Add the new listener to the Trace.Listeners collection. Trace.Listeners.Add(myListener) flush the Trace buffer by calling the Flush method to write output to the text file. Trace.Flush() ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 45 of 50
  • 46. Exception Handling, Debugging and Testing Windows Applications Logging Trace Output to an EventLog • You use the EventLogTraceListener class to log the trace output to an EventLog object. • To log the trace output to an EventLog, the following steps must be performed: 1. Create an instance of a EventLog object and assign it to a new event log or an existing event log. Dim myLog As New EventLog (“Event Log”) 2. Set the Source property of the EventLog. myLog.Source = “Trace Output” 3. Create an instance of EventLogTraceListener that specifies the new log as its target. Dim myListener As New EventLogTraceListener(myLog) 4. Add the new listener to the Trace.Listeners collection. Trace.Listeners.Add(myListener) ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 46 of 50
  • 47. Exception Handling, Debugging and Testing Windows Applications Implementing Trace Switches • Trace switches allow you to enable, disable, and filter tracing output. • Two types of trace switches are provided in the .NET Framework: • BooleanSwitch Class: The BooleanSwitch class acts as a toggle switch that may either enable or disable a variety of trace statements. • TraceSwitch Class: The TraceSwitch class allows you to enable a trace switch for a particular tracing level. • To use the BooleanSwitch or the TraceSwitch class you need to create an instance of these classes. • The TraceSwitch class exposes four read-only properties that represent the Trace levels. These are: • TraceSwitch.TraceError Property • TraceSwitch.TraceWarning Property • TraceSwitch.TraceInfo Property • TraceSwitch.TraceVerbose Property ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 47 of 50
  • 48. Exception Handling, Debugging and Testing Windows Applications Summary In this lesson, you learned that: • The types of errors that can occur in an application are syntax errors, run- time errors, and logical errors. • An exception is an abnormal condition that an application encounters during execution. • Exception handling is the process of providing an alternate path to be executed when the application is not able to execute in the desired way. • Visual Basic .NET provides two methods to handle exceptions: • Structured exception handling • Unstructured exception handling • In addition to handling pre-defined exceptions, users can create their own exceptions by deriving an exception class from the ApplicationException class. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 48 of 50
  • 49. Exception Handling, Debugging and Testing Windows Applications Summary (Contd.) • Once an application has been coded, it must be tested to ensure that it fulfills the requirements for which it was designed and meets quality expectations. • There are various types of testing that an application has to go through. These include unit testing, integration testing, regression testing and acceptance testing. • For testing to be successful, a test plan must be created that outlines the entire process of testing and includes budget, schedule and performance considerations. • In order to assist you in debugging logical and runtime errors, Visual Basic .NET provides extensive debugging tools. You can use the Visual Basic .NET Debug toolbar to access these tools. • By using the debugging tools, you can perform the following actions: • Start execution • Step through execution • Stop execution ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 49 of 50
  • 50. Exception Handling, Debugging and Testing Windows Applications Summary (Contd.) • You can log informative messages about your application’s conditions at run time by using tracing. • Tracing can be implemented by using the Trace and Debug classes. • The Listeners collection is a group of classes capable of receiving output from the Debug and Trace classes. • Trace switches allow you to enable, disable, and filter tracing output. • Conditional compilation is a means of selectively compiling portions of your program code. This can be used for creating multiple versions of your application without the need to maintain multiple copies of code. ©NIIT Enhancing and Distributing Applications Lesson 1B / Slide 50 of 50