Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Exception Handling » ASP.NET and VB.NET Error Handling

ASP.NET and VB.NET Error Handling

ASP.NET and VB.NET both are providing excellent error handling options when compared with ASP and VB6. In VB.NET we can make use of the structured way of error handling with the Try & Catch statement.

Total page views :  58289
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Download Free Book

Introduction

One of the main features of ASP.NET over ASP is it's new error handling features. The only way to capture errors in the ASP/VBScript was using the "On Error Resume Next" statement and checking each line for an error with "If Err.Number <> 0 Then " statements. Developers who where using JScript instead of the VBScript at the server-side where lucky. They've had access to the "Try... Catch" statements provided by JScript. Well it's all over now. Now all the .NET enabled languages support better error handling statements including VB.NET. Now, VB.NET supports the "Try...Catch" statement. On top of this ASP.NET configuration file also supports ASP.NET level error handling. Let's see all of them one by one.

VB.NET Error Handling

In the previous versions of VB we had several flavors of "On Error" statements to handle error in a non-structured way. But in VB.NET we can make use of the structured way of error handling with the Try & Catch statement.

Here is an example for this.

Sub DoSomething()
Try
'Do Something
Catch e As Exception
'Catch the error and display it.
Response.Write("An Error Occurred: " & e.toString())
Finally
'Do the final cleanup such as closing the Database connection
End Try
End
Sub

The above code is the simplest form of structured error handling in VB.NET. We're doing our processing in the Try Block. If anything goes wrong in the Try block, the Catch block will be called and the error will be handled. After that the "Finally" block will be called to do the cleanup.

We can also filter the error handling based on the type of exceptions. For example, Let's say we're accessing data from SQL Server 2000 and we're writing the data into a text file. In this process there could be three kids of error.

  1. SQL Server related Errors.
  2. File IO Errors.
  3. Other generic errors.

We can filter the errors based on their categories in the Catch block. Let's see an example for this.

Sub DoSomething()
Try
'Do Something
Catch SQLExp As SQLException
'Catch the error and display it.
Response.Write("An SQL Server Error Occurred: " & e.toString())
Catch IOExp As IOException
'Catch the error and display it.
Response.Write("An File IO Error Occurred: " & e.toString())
Catch e As Exception'Catch the error and display it.
Response.Write("An Error Occurred: " & e.toString())
Finally
'Do the final cleanup such as closing the Database connection
End Try
End
Sub

As you can see we've categorized our error handling based on the errors. The "Catch SQLExp as SQLException" block will handle all the SQL Server errors and all File IO errors will be handled by "Catch IOExp as IOException" block. The SQLException and IOExpection classes are defined in the "System.Data.SQL" and "System.IO" namespaces. We can further customize the errors based on the error numbers,

Sub DoSomething()
Try
'Do Something
Catch SQLExp As SQLException
If SQLExp.Number = 1212 Then
Response.Write("SQL Server Error 1212 Occurred: " & e.toString())
Else
'Catch the error and display it.
Response.Write("An SQL Server Error Occurred: " & e.toString())
End If
Catch IOExp As IOException
'Catch the error and display it.
Response.Write("An File IO Error Occurred: " & e.toString())
Catch e As Exception
'Catch the error and display it.
Response.Write("An Error Occured: " & e.toString())
Finally
'Do the final cleanup such as closing the Database connection
End Try
End
Sub

OR

Sub DoSomething()
Try
'Do Something
Catch When Err = 1212
Response.Write("SQL Server Error 1212 Occurred: " & e.toString())
Catch SQLExp As SQLException
'Catch the error and display it.
Response.Write("An SQL Server Error Occurred: " & e.toString())
Catch IOExp As IOException
'Catch the error and display it.
Response.Write("An File IO Error Occurred: " & e.toString())
Catch e As Exception
'Catch the error and display it.
Response.Write("An Error Occurred: " & e.toString())
Finally
'Do the final cleanup such as closing the Database connection
End Try
End
Sub

We can use the "Exit Try" statement in the "Catch" block to exit from the "Try....Catch" structure. When the "Exit Try" statement encountered by the runtime, the statement next to the "End Try" will be executed and the "Finally" block will not be executed.

ASP.NET Error Handling options

ASP.NET provides better support for tracking runtime errors and handling them. This gives us more power to display customized messages to the site users rather than seeing the error messages like "BC30311: A value of type .....".
By default, when an error occurs in ASP.NET code, ASP.NET show the error message and it'll also highlights the code line of code causing the error. For example, in the page_load event, we've used the following code.

Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
Dim Myobj As New MyObject
Myobj.DoSomthing()
End Sub

MyObject was not defined in any of the namespaces. So, I should get a compilation error. Here is how ASP.NET shows the error message.



ASP.NET shows the error message and it also shows the line of code that causes the error including the line number. You'll see this error message only if you are accessing the site locally like "http://localhost/YourApp/". If you access the site with it's IP address like http://xx.xx.xx.xx/YourApp/ then, you'll not see the above message. Instead you'll see something like this.



ASP.NET hides all your application information (Your code), when your site is accessed from out side world. It only shows the application specific error message if you access the site locally. When you are developing the ASP.NET application, you may sit in a different machine than the one hosted the ASP.NET. In these cases you may want to see the error messages outside of the local machine also. Well, if you want to show the error messages outside the local machine then you can set the set the <customerrors> tags mode attribute to "off" in WEB.CONFIG.

<configuration>
<customerrors mode="off" />
</
configuration>

Custom Error page

The default message showed by ASP.NET may make sense in the development environment and it many not make any sense to the end users of the site. In that case, ASP.NET allows us to configure a default error-handling page for your site. We can specify the error page like this in WEB.CONFIG.

<configuration>
<customerrors mode="on" defaultredirect="error.aspx" />
</
configuration>

So, when an un-handled error occurs in ASP.NET application "Error.ASPX" error page will be displayed. After we've changed the configuration in the WEB.CONFIG, here is how the above error pages looks like.



Of course, we can make this page prettier some meaningful content to the end user of your site.

The mode attribute in the <customerrors> tag can have two options. The difference is shown in the following table.

Mode attribute Localhost  IP Address
remoteonly The error message from the compiler and the code that is causing the error will be showed. Custom error page will be showed.
on Custom error page will be showed. Custom error page will be showed.


Final Note

ASP.NET and VB.NET both are providing excellent error handling options when compared with ASP and VB6.

Until next time, Happy Programming!


Login to add your contents and source code to this article
 About the author
 
Srinivasa Sivkumar
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
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.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
mbmnbm by v On July 25, 2007
Catch ex As Exception nbbbnmb mbnm bnm nb mb End Try
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved