|
|
|
|
|
Home
»
VB.NET
»
Best practices of Exception Management in VB.NET
|
|
|
|
Total page views :
33227
|
|
Total downloads :
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Introduction
Exception management is one of the key area for all kinds of application development .You should adopt an appropriate strategy for exception management to build high quality and robust application .It is a very powerful concept and makes the development work very easy if its used efficiently. Inappropriate way of handling exception can degrade the performance. Before dig into this its very important to know what is an exception? The general meaning of "an exception is the breaching of predefined assumption of the application". Remember exception and error are not the same. To explain this let me explain couple of examples.
Example 1
Lets say you are try to log data to a file and your application assumes the file is present in the target path , but if is not then exception would be raised .On the other hand if your job is to trace the file and if it is present then log the data in this scenario raising an exception is a bad coding practice. It should be handled through validation code.
Example 2
Lets say in a normal ASP.NET application you are trying to update all necessary fields to the database , and your application assume the database connection is available suppose the connection is not available then raising an exception is a ideal solution. On the other hand while update the mandatory fields in database and few of them having the null values then raising an exception is not necessary it should be handled through validation code.
How to Handle
As a developer you must take the advantage of structured exception handling mechanism through try, catch and finally block. The .NET framework provides a broad hierarchy of exception classes to handle the different types of exception and all these classes derived from Exception class (base class). The developer can extend exception mechanism through inheritance, it helps to implement the custom error handling or provide a proper gateway to handle the complex error handling for the application. Unfortunately, many developers misuse this architecture capability .One very important thing you should keep in mind is how to react when a exception occur at runtime. The good approach to react the exception is
- Just ignore the exception or implement different possible catch blocks to catch the exception
- Catch the exception and perform required action for your application and if you can not recover from the exception rethrow the exception.
- Catch the exception and wrap with another exception which is more relevant for your application. Exception wrapping used to avoid breaking the layer abstraction due to exception. For preserving the original exception you can use the InnerException property of the exception class this allows the original exception to be wrapped inside a new exception (which is more relevant for your application) to understand the wrapping of exception lets look at this example inside a method of your application caught a lower level exception called IOException , you can wrap this original exception with a application level exception called LoadingException or FailtoLoadInfo exception or something else which is more relevant for your application rather then alerting the lower level exception to the user.
The exception management architecture of a application capable to
- Detect Exception
- Perform code clean up
- Wrap one exception inside another
- Replace one exception with another
- Logging and reporting error information
- Generating events that can be monitored externally to assist system operation
At the beginning of the design you must plan for a consistency and robust exception management architecture and it should be well encapsulated and abstract the details of logging and reporting throughout all architecture layer of your application .Lets discuss some of the best practices of exception
Best Practices
The following list contains tips/suggestions to be consider while handling the exceptions:
- Exception is a expensive process , for this reason, you should use exceptions only in exceptional situations and not to control regular logic flow. For example
Private Sub EmpExits(ByVal EmpId As String) '... search for employee If dr.Read(EmpId) =0 Then ' no record found, ask to create Throw(New Exception("Emp Not found")) End If End Sub
The best practice is :
Private Function EmpExits(ByVal EmpId As String) As Boolean '... search for Product If dr.Read(EmpId) =0 Then ' no record found, ask to create Return False End If End Function
- Avoid exception handling inside loops, if its really necessary implement try/catch block surround the loop
- Adopt the standard way of handling the exception through try, catch and finally block .This is the recommended approach to handle exceptional error conditions in managed code, finally blocks ensure that resources are closed even in the event of exceptions. For example
Private conn As SqlConnection = New SqlConnection("...") Try conn.Open() '.some operation ' ... some additional operations Catch e1 As ' handle the exception Finally If conn.State=ConnectionState.Open Then conn.Close() ' closing the connection End If End Try
- Where ever possible use validation code to avoid unnecessary exceptions .If you know that a specific avoidable condition can happen, precisely write code to avoid it. For example, before performing any operations checking for null before an object/variable can significantly increase performance by avoiding exceptions. For example
Private result As Double = 0 Try result = firstVal/secondVal Catch e As System.Exception handling the zero divided exception End Try This is better then the above code Private result As Double = 0 If secondVal >0 Then result = firstVal/secondVal Else result = System.Double.NaN End If
- Do not rethrow exception for unnecessary reason because cost of using throw to rethrow an existing exception is approximately the same as creating a new exception and rethrow exception also makes very difficult to debug the code. For example
Try
' Perform some operations ,in case of throw an exception.... Catch e As Exception ' Try to handle the exception with e Throw End Try
- The recommended way to handle different error in different way by implement series of catch statements this is nothing but ordering your exception from more specific to more generic for example to handle file related exception its better to catch FileNotFoundException, DirectoryNotFoundException, SecurityException,IOException, UnauthorizedAccessException and at last Exception.
- ADO.NET errors should be capture through SqlException or OleDbException.
- Use the ConnectionState property for checking the connection availability instead of implementing an exception
- Use Try/Finally more often, finally provides option to close the connection or the using statement provides the same functionality.
- Use the specific handler to capture specific exception, in few scenarios if you know that there is possibility for a specific error like database related error it can be catch through SqlException or OleDbException as below
Try
... Catch sqlexp As SqlException ' specific exception handler ... Catch ex As Exception ' Generic exception handler ... End Try
- Your exception management system capable to detect, wrap one exception inside another, Replace one exception with another, logging and reporting the exception information for monitoring the application.
- Its recommend to use "Exception Management Application Block" provided by Microsoft .It is a simple and extensible framework for logging exception information to the event log or you can customize to write the exception information to other data sources without affecting your application code and implemented all best practices and tested in Microsoft Lab.
For more information
NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
Anand Kumar Rao
I am having 6 yrs of experience on oops environment .My core expertise is developing robust service components using ATL COM ,Remoting and Web Service and very much passionate about Microsoft Patterns and Practices. Apart from my regular work I am actively participating various Microsoft User Groups and sharing my knowledge and articles on best practices in C# and ASP.NET.
|
|
|
|
|
|
|
|
|
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.
|
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from
DevExpress - Absolutely Free-of-Charge without any royalties or distribution
costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin
edit, tab control and so much more!
DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
|
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.
|
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|