Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

.NET Exceptions

By Exforsys | on July 5, 2005 |
VB.NET 2005

.NET Exceptions

In this tutorial you will learn about Exceptions, Common Exceptions, Handling Exceptions – Try Block, Catch Block, Throw Statement, Finally Block, Salient points about error handling Custom Exceptions – Managing Unhandled Exception

Exceptions

Abnormal conditions can become obstacles in the execution of very good programs. These conditions may force the program to breakdown, or halt or just go into a limbo. The Network connection may snap or a printer may run out of paper. No programmer can foresee these problems, yet he must give the user an option to gracefully save the work done up to the point and exit the program. The Exception Management Application Block provides a simple yet extensible framework for handling exceptions in VB.NET.

What is an Exception?

Programs are designed to execute normally in predefined conditions. However, the program may occasionally be confronted with an abnormal situation which it is not built to handle. Such a situation will result in an “exception” to the norm. Programs will have to be told what it has to do when it encounters such abnormal conditions. The process of anticipating and providing for handling such extraordinary situations is known as exception handling. In .Net Framework 2005 we have a facility to break, correct the code and continue in case of exception. This facility was withdrawn in the earlier releases of .Net Framework.

An exception may occur due to a logical or a syntax error. Where syntax errors may be caught by the complier, logical errors are likely to be missed Therefore, you may have a program that may be trying to delete a file that does not exist or it may be trying to divide by zero or it may just be a null pointer error or a System IO exception. The program must be told what to do and how to do it. Some of these code level bugs come to light only at the time of execution or under extreme conditions. Most programmers as a matter of caution create exceptions and raise them on some predefined conditions to monitor the working of the program. They ensure that they provide for exception handling for the most commonly encountered problems and situations. Microsoft .NET framework 2005 has made this task of the programmer easier by building into the application the Exception Assistant.

An example of an exception handler code is illustrated below for your understanding:

Click here for Sample Code

In the above example a class has been instantiated and the SecondMethod is called. In the above code two variables a and b are passed on to the SecondMethod and a process is initiated in the SUB. Once this process is complete the SUB FirstMethod is called. The expected condition here is that the value of ‘n’ should not be zero. If at this point the value of “n” is set to zero the program will breakdown or terminate.

The Exception Assistant helps the programmer troubleshoot exceptions and also helps him understand more about the exceptions.

Some of the most common exceptions are listed below:

  • Code Access Security Exceptions
  • MicroSoft.Tools.CannotRemoveControlException
  • System.AccessViolationException
  • System.ArrayTypeMismatchExceptionSystem.Data.OleDb.OleDbException
  • System.Data.ConstraintException
  • System.Data.InvalidExpressionExcepton
  • System.Data.NoNull.AllowedException
  • System.Data.OdbcExcepton
  • System.Data.OracleClient.OracleException
  • System.DivideByZeroException
  • System.DuplicateWaitObjectException
  • System.IO.DirectroyNotFoundException
  • System.IO.EndOfStreamException
  • System.IO.FileNotFoundException
  • System.IO.IOException
  • System.IO.PathTooLongException
  • System.IO.InternalBufferOverflowException
  • System.NotSupportedException
  • NullReferenceException
  • System.ObjectDisposedException
  • System.OperationCalnceledException
  • System.OutOfMemoryException
  • System.OverflowException
  • System.Security.SecurityException
  • System.StackOverFlowException
  • System.UnauthorizedException

Handling Exceptions

Visual Basic supports both Structured and unstructured exception handling. If an exception occurs in a method that is not equipped to handle it, the exception is propagated back to the calling method, or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method’s caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.

The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes invalid.

In the Structured Exception Handling, the blocks of code are encapsulated with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other.

Using the Try…Catch…Finally statement, you can protect blocks of code that have the potential to raise errors. You can nest exception handlers, and the variables declared in each block will have local scope.

.

.


The Try Block

The try block can be defined as code that can possibly raise exceptions—for instance mathematical calculations, Database Connection and queries, Writing to a log file, or reading from a file. The Try block, the Catch block and the Finally… function together to handle the exception.

The Catch Block

A single Try block can have more than one catch block. If an error occurs during execution of any of the code in this section, Visual Basic examines each Catch statement within the Try…Catch…Finally until it finds one whose condition matches that error. If one is found, control transfers to the first line of code in the Catch block. If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try…Catch…Finally block that contains the block in which the exception occurred. This process continues through the entire stack until a matching Catch block is found in the current procedure. If none is found, an error is produced. General exception handler to catch any other exceptions can also be added.

The Throw Statement

You can also explicitly use a throw statement to throw or re-throw an exception. Let us see an example for this now. Any exception that prevents further flow of information is automatically thrown which are handled in the try catch finally blocks. However user generated exceptions are used to be thrown in this fashion. You need do explicitly use throw statement to throw these exceptions that will be handled by the try catch finally blocks. For this purpose you need to create a new object based on the ApplicationException Object.

Click here for Sample Code

The Finally Block

The code in the Finally block is always executed at the end, just before the error handling block loses scope, irrespective of whether the code in Catch blocks has executed or not. This block is normally used to clean up the code.

Salient points about error handling:

  1. Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a variable in more than one block, declare the variable outside the Try…Catch…Finally structure.

  2. If errors occur that the programmer has not handled, Visual Studio for Applications simply provides its normal error message to a user, as if there was no error handling.
  3. The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The exception argument is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in the Try block. The Exception class instance contains information about the error including, among other things, its number and message.
  4. In partial trust situations, such as an application hosted on a network share, Try…Catch…Finally will not catch security exceptions that occur before the method containing the call is invoked.

     

Custom Exceptions

The exceptions that are raised can be classified in to two categories.

Managing Unhandled Exceptions

Microsoft recommends that programmers should handle unhandled exceptions in a single error handler. They further state that the user should be given the option of continuing with the program or exiting the program when such an error is encountered. Consider a simple Windows Forms application containing a single form with two buttons and a text box. The Add button just adds text to the text box. The Remove button clears it. Normally this would be caught by a try-catch block. By writing an unhandled exception delegate, this can be dispensed with. The signature for the delegate looks like this.

Click here for Sample Code

Unhandled exceptions events can be moved into an assembly wide class so that it can be accessed by other forms. The unhandled exception generates an AbortIgnoreRetry dialog box giving the full description of the error.


« « Getting started with ASP.NET 2.0
Career Track: Computer Programmer » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • Visual Studio.NET Namespaces

    June 7, 2005 - 0 Comment
  • .NET Assemblies

    July 7, 2005 - 0 Comment
  • DomainUpDown and NumericUpDown Controls

    June 27, 2005 - 0 Comment
  • Using XML Data

    July 14, 2005 - 0 Comment
  • Customizing Setup Project in Visual Studio.NET 2005

    August 4, 2005 - 0 Comment
  • Visual Studio Windows Forms Designer

    June 7, 2005 - 0 Comment
  • Simple Data Binding

    July 7, 2005 - 0 Comment
  • .NET Common Windows Forms Controls Part 2

    July 2, 2005 - 0 Comment
  • Web Services – SOAP, WSDL, Disco and UDDI

    July 16, 2005 - 0 Comment
  • Deploying Windows Applications In Visual Studio.NET 2005

    August 3, 2005 - 0 Comment
  • Microsoft .NET Creating Installation Components

    August 10, 2005 - 0 Comment
  • Shared Assembly

    August 9, 2005 - 0 Comment
  • The File Types Editor

    August 9, 2005 - 0 Comment
  • Tracing VB.NET Windows Application

    August 9, 2005 - 0 Comment
  • VB.NET Windows Application Testing

    August 9, 2005 - 0 Comment
  • The Registry Editor in Visual Studio.NET 2005

    August 4, 2005 - 0 Comment
  • Customizing Setup Project in Visual Studio.NET 2005

    August 4, 2005 - 0 Comment
  • Deploying Windows Applications In Visual Studio.NET 2005

    August 3, 2005 - 0 Comment
  • Debugging Windows Applications In Visual Studio.NET 2005

    August 3, 2005 - 0 Comment
  • Working with Legacy Code and COM Components

    July 30, 2005 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Microsoft .NET Creating Installation Components
  • Shared Assembly
  • The File Types Editor
  • Tracing VB.NET Windows Application
  • VB.NET Windows Application Testing

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT