Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Visual Basic Language » Exception Statements in VB.NET: Part 2

Exception Statements in VB.NET: Part 2

In this article I will explain you about Exception Statements in VB.NET.

Author Rank :
Page Views : 1035
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


As you learn about the Exception in my previous article now learn what if you want to change this behavior? This leads us to the next important concept, checked and unchecked statements in VB.NET.

The different ways of controlling overflow behavior are listed below:

  • Set the compiler option to checked + or checked -
     

  • Add the checked statement and unchecked statement to your code Compiler options apply to the application level whereas checked and unchecked statements can apply to specific blocks of code. Checked and unchecked statements always override the compiler options, so if you have compiled with the checked+ option and have a block of code surrounded by an unchecked statement, the overflow exception will not be raised for any overflow conditions within the unchecked block. Similarly, if you have compiled with the checked– option and have a block of code surrounded by the checked statement, the overflow exception would be raised for any overflow conditions within the checked block of code. The next example shows what the code looks like after adding the checked statement.

Exception3.VB, Checked-Unchecked Example

    Imports System
    Imports System.Text

    Public Class LearnAboutTryCatch1
        Public Shared Sub GenerateException(ByVal arg1 As Int32, ByVal arg2 As Int32)
            Dim result1 As Int32 = 0
            Dim result2 As Int32 = 0
            Try
                'BLOCK OF CODE WHERE ERRORS ARE EXPECTED
                'division
                result1 = arg1 / arg2
                'multiplication
                result2 = arg1 * arg2
                Console.WriteLine(result1)
                Console.WriteLine(result2)
            Catch e As System.DivideByZeroException
                'HANDLE THE ERROR
                'StackTrace gives us the location of error
                ' as string
                'e.Message: gives the error message in this
                ' case, Attempted to divide by zero.
                'e.Stacktrace: gives the location of the error
                ' in text form. In this case at
                ' LearnAboutTryCatch1.GenerateDivideByZeroError(
                ' Int32 Numerator,Int32 Denominator)
                'in this case the output would be
                'Attempted to divide by zero. at
                ' LearnAboutTryCatch1.GenerateDivideByZeroError(
                ' Int32 Numerator,Int32 Denominator)
                Console.WriteLine([String].Concat(e.Message, e.StackTrace))
            Catch e As System.OverflowException
                'HANDLE THE ERROR
                'StackTrace gives us the location of error as
                'string.
                'e.Message: gives the error message in this
                ' case,
                'e.Stacktrace: gives the location of the error
                ' in text form.
                Console.WriteLine([String].Concat(e.Message, e.StackTrace))
            End Try
        End
Sub
        Public
Shared Sub Main()
            GenerateException(6, 0)
            GenerateException(999999999, 999999999)
            Console.ReadLine()
        End Sub
    End
Class

Output

ex2.gif

The code above would raise both exceptions: the divide-by-zero exception and the overflow exception. We leave it to you as an exercise to play with different combinations of compiler options, as well as checked and unchecked statements.

Now, let's say we want to capture all other exceptions other than the specific exceptions described here (DivideByZeroException and OverflowException). To do that we have to add another catch statement with the argument of type System.Exception. By adding the System.Exception, the code now will look like next example. Pay specific attention to the place where we insert the catch statement.

Exception4.VB, General Exception Example

    Imports System
    Imports System.Text

    Public Class LearnAboutTryCatch1
        Public Shared Sub GenerateException(ByVal arg1 As Int32, ByVal arg2 As Int32)
            Dim result1 As Int32 = 0
            Dim result2 As Int32 = 0
            Try
                'BLOCK OF CODE WHERE ERRORS ARE EXPECTED
                'division
                result1 = arg1 / arg2
                'multiplication
                result2 = arg1 * arg2
                Console.WriteLine(result1)
                Console.WriteLine(result2)
                Catch e As System.DivideByZeroException
                'HANDLE THE ERROR
                'StackTrace gives us the location of error as string
                'e.Message: gives the error message, in this
                ' case, Attempted to divide by zero.
                'e.Stacktrace: gives the location of the error in text form. In
                ' this case at LearnAboutTryCatch1.GenerateDivideByZeroError(
                ' Int32 Numerator,Int32 Denominator)
                'in this case the output would be
                'Attempted to divide by zero. at
                ' LearnAboutTryCatch1.GenerateDivideByZeroError(
                ' Int32 Numerator,Int32 Denominator)
                Console.WriteLine([String].Concat(e.Message, e.StackTrace))
            Catch e As System.OverflowException
                'HANDLE THE ERROR
                'stackTrace gives us the location of error as string
                'e.Message: gives the error message in this case,
                'e.Stacktrace: gives the location of the error in text
                ' form.
                Console.WriteLine([String].Concat(e.Message, e.StackTrace))
            End Try
        End
Sub
        Public
Shared Sub Main()
            GenerateException(6, 0)
            GenerateException(999999999, 999999999)
            Console.ReadLine()
        End Sub
    End
Class

Output of above example:

ex2.gif

The compiler would not let you compile the code above. Instead, it would give you the following error message: "A previous catch clause already catches all exceptions of this or a super type ('System.Exception')." The lesson to learn is you have to first catch specific exceptions and then catch the general exception (System.Exception). We leave it as an exercise for you to change the code above to fix the order of catching exceptions.

As shown in next example, there are two ways to catch a general System.Exception. In the first case you would capture the exception and get all the information about it from the Exception parameter. However, in the second code block you would not have access to that information.

Try-Catch Syntax

    Try
        Catch

    End Try

Conclusion

Hope this article would have helped you in understanding Exception Statements in VB.NET.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sapna
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.