The Wayback Machine - https://web.archive.org/web/20170610013220/http://dotnet.sys-con.com:80/node/4050270

Welcome!

Microsoft Cloud Authors: Andreas Grabner, Stackify Blog, Liz McMillan, David H Deans, Automic Blog

Related Topics: @DevOpsSummit, Microsoft Cloud, Containers Expo Blog

@DevOpsSummit: Blog Feed Post

C# Exception Handling Best Practices | @DevOpsSummit #APM #Monitoring

Basics about C# Exceptions, including examples of common .NET Exceptions and how to create your own custom C# Exception types

C# Exception Handling Best Practices
By Matt Watson

Welcome to Stackify's guide to C# exception handling. In this article we cover the following topics:

  • Basics about C# Exceptions, including examples
  • Common .NET Exceptions
  • How to Create Your Own Custom C# Exception Types
  • How to Find Hidden .NET Exceptions
  • C# Exception Logging Best Practices

What Is an Exception?
Exceptions are a type of error that occurs during the execution of an application. Errors are typically problems that are not expected. Whereas, exceptions are expected to happen within application code for various reasons.

Applications use exception handling logic to explicitly handle the exceptions when they happen.  Exceptions can occur for a wide variety of reasons. From the infamous NullReferenceException to a database query timeout.

The Anatomy of C# Exceptions
Exceptions allow an application to transfer control from one part of the code to another. When an exception is thrown, the current flow of the code is interrupted and handed back to a parent try catch block. C# exception handling is done with the follow keywords: try, catch, finally, and throw

  • try - A try block is used to encapsulate a region of code. If any code throws an exception within that try block, the exception will be handled by the corresponding catch.
  • catch - When an exception occurs, the Catch block of code is executed. This is where you are able to handle the exception, log it, or ignore it.
  • finally - The finally block allows you to execute certain code if an exception is thrown or not. For example, disposing of an object that must be disposed of.
  • throw - The throw keyword is used to actually create a new exception that is the bubbled up to a try catch finally block.

Example #1: The Basic "try catch finally" Block
The C# try and catch keywords are used to define a try catch block. A try catch block is placed around code that could throw an exception. If an exception is thrown, this try catch block will handle the exception to ensure that the application does not cause an unhandled exception, user error, or crash the application.

Below is a simple example of a method that may throw an exception and how to properly use a try catch finally block for error handling.

WebClient wc = null;
try
{
wc = new WebClient(); //downloading a web page
var resultData = wc.DownloadString("http://google.com");
}
catch (ArgumentNullException ex)
{
//code specifically for a ArgumentNullException
}
catch (WebException ex)
{
//code specifically for a WebException
}
catch (Exception ex)
{
//code for any other type of exception
}
finally
{
//call this if exception occurs or not
//in this example, dispose the WebClient
wc?.Dispose();
}

Your exception handling code can utilize multiple C# catch statements for different types of exceptions. This can be very useful depending on what your code is doing. In the previous example, ArgumentNullException occurs only when the website URL passed in is null. A WebException is caused by a wide array of issues. Catching specific types of exceptions can help tailor how to handle them.

Example #2: Exception Filters
One of the new features in C# 6 was exception filters. They allow you have even more control over your catch blocks and further tailor how you handle specific exceptions. This can help you fine-tune exactly how you handle exceptions and which ones you want to catch.

Before C# 6, you would have had to catch all types of a WebException and handle them. Now you could choose only to handle them in certain scenarios and let other scenarios bubble up to the code that called this method. Here is a modified example with filters:

WebClient wc = null;
try
{
wc = new WebClient(); //downloading a web page
var resultData = wc.DownloadString("http://google.com");
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.ProtocolError)
{
//code specifically for a WebException ProtocolError
}
catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
{
//code specifically for a WebException NotFound
}
catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.InternalServerError)
{
//code specifically for a WebException InternalServerError
}
finally
{
//call this if exception occurs or not
wc?.Dispose();
}

Common .NET Exceptions
Proper exception handling is critical to all application code. There are a lot of standard exceptions that are frequently used. The most common being the dreaded null reference exception. These are some of the common C# Exception types that you will see on a regular basis.

The follow is a list of common .NET exceptions:

  • System.NullReferenceException - Very common exception related to calling a method on a null object reference
  • System.IndexOutOfRangeException - Occurs attempting to access an array element that does not exist
  • System.IO.IOException - Used around many file I/O type operations
  • System.Net.WebException - Commonly thrown around any errors performing HTTP calls
  • System.Data.SqlClient.SqlException - Various types of SQL Server exceptions
  • System.StackOverflowException - If a method calls itself recursively, you may get this exception
  • System.OutOfMemoryException - If your app runs out of memory
  • System.InvalidCastException - If you try to cast an object to a type that it can't be cast to
  • System.InvalidOperationException - Common generic exception in a lot of libraries
  • System.ObjectDisposedException - Trying to use an object that has already been disposed

How to Create Your Own C# Custom Exception Types
C# exceptions are defined as classes, just like any other C# object. All exceptions inherit from a base System.Exception class. There are many common exceptions that you can use within your own code. Commonly, developers use the generic ApplicationException or Exception object to throw custom exceptions. You can also create your own type of exception.

Creating your own C# custom exceptions is really only helpful if you are going to catch that specific type of exception and handle it differently. They can also be helpful to track a very specific type of exception that you deem to extremely critical. By having a custom exception type, you can more easily monitor your application errors and logs for it with an error monitoring tool.

We have created a few custom exception types. One good example is a ClientBillingException. Billing is something we don't want to mess up, and if it does happen, we want to be very deliberate about how we handle those exceptions.

By using a custom exception type for it, we can write special code to handle that exception. We can also monitor our application for that specific type of exception and notify the on-call person when it happens.

Benefits of custom C# Exception types:

  • Calling code can do custom handling of the custom exception type
  • Ability to do custom monitoring around that custom exception type

Here is a simple example from our code:

public void DoBilling(int clientID)
{
Client client = _clientDataAccessObject.GetById(clientID);

if (client == null)
{
throw new ClientBillingException(string.Format("Unable to find a client by id {0}", clientID));
}
}

public class ClientBillingException : Exception
{
public ClientBillingException(string message)
: base(message)
{
}
}

How to Find Hidden .NET Exceptions

What Are First Chance Exceptions?
It is normal for a lot of exceptions to be thrown, caught, and then ignored. The internals of the .NET Framework even throws some exceptions that are discarded. One of the features of C# is something called first chance exceptions. It enables you to get visibility into every single .NET Exception being thrown.

It is very common for code like this below to be used within applications. This code can throw thousands of exceptions a minute and nobody would ever know it. This code is from another blog post about an app that had serious performance problems due to bad exception handling. Exceptions will occur if the reader is null, columnName is null, columnName does not exist in the results, the value for the column was null, or if the value was not a proper DateTime. It is a minefield.

public DateTime? GetDate(SqlDataReader reader, string columnName)
{
DateTime? value = null;
try
{
value = DateTime.Parse(reader[columnName].ToString());
}
catch
{
}
return value;
}

How to Enable First Chance Exceptions with Visual Studio
When you run your application within Visual Studio, with the debugger running, you can set Visual Studio to break anytime a C# Exception is thrown. This can help you find exceptions in your code that you did not know existed.

To access Exception Settings, go to Debug -> Windows -> Exception Settings

Under "Common Language Runtime Exceptions" you can select the types of exceptions you want the debugger to break for automatically. I would suggest just toggling the checkbox for all. Once you break on an exception, you can then tell it to ignore that particular type of exception to exclude it, if you would like.

How to View All Exceptions with Prefix
Our free .NET profiler can also show you all of your exceptions. To learn more, check out this blog post: Finding Hidden Exceptions in Your Application with Prefix

The Retrace solution for your servers can also collect all first chance exceptions via the .NET profiler. Without any code or config changes, it can automatically collect and show you all of your exceptions.

How to Subscribe to First Chance Exceptions in Your Code
The .NET Framework provides a way to subscribe to an event to get a callback anytime an Exception occurs. You could use this to capture all of the exceptions. I would suggest potentially subscribing to them and just outputting them to your Debug window. This would give you some visibility to them without cluttering up your log files.

I would suggest potentially subscribing to them and just outputting them to your Debug window. This would give you some visibility to them without cluttering up your log files. You only want to do this once when your app first starts in the Main() method of a console app, or startup of an ASP.NET web app.

AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
Debug.WriteLine(eventArgs.Exception.ToString());
};

C# Exception Logging Best Practices
Proper exception handling is critical for any application. A key component to that is logging the exceptions to a logging library so that you can record that the exceptions occurred. Please check out our guide to C# Logging Best Practices to learn more on this subject.

We suggest logging your exceptions using NLog, Serilog, or log4net. All three frameworks give you the ability to log your exceptions to a file. They also allow you to send your logs to various other targets. These things like a database, Windows Event Viewer, email, or an error monitoring service.

Every exception in your app should be logged. They are critical to finding problems in your code!

It is also important to log more contextual details that can be useful for troubleshooting an exception. Things like what customer was it, key variables being used, etc.

try
{
//do something
}
catch (Exception ex)
{
//LOG IT!!!
Log.Error(string.Format("Excellent description goes here about the exception. Happened for client {0}", _clientContext.ClientId), ex);
throw; //can rethrow the error to allow it to bubble up, or not, and ignore it.
}

To learn more about logging contextual data, read this blog post: What is structured logging and why developers need it

Why Logging Exceptions to a File Is Not Enough
Logging your exceptions to a file is a good best practice. However, this is not enough once your application is running in production. Unless you log into every one of your servers every day and review your log files, you won't know that the exceptions occurred. That file becomes a black hole.

An error monitoring service is a key tool for any development team. They allow you to collect all of your exceptions in a central location.

  • Centralized exception logging
  • View and search all exceptions across all servers and applications
  • Uniquely identify exceptions
  • Receive email alerts on new exceptions or high error rates

The post C# Exception Handling Best Practices appeared first on Stackify.

Read the original blog entry...

More Stories By Stackify Blog

Stackify offers the only developers-friendly solution that fully integrates error and log management with application performance monitoring and management. Allowing you to easily isolate issues, identify what needs to be fixed quicker and focus your efforts – Support less, Code more. Stackify provides software developers, operations and support managers with an innovative cloud based solution that gives them DevOps insight and allows them to monitor, detect and resolve application issues before they affect the business to ensure a better end user experience. Start your free trial now stackify.com

@ThingsExpo Stories
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
In this presentation, Striim CTO and founder Steve Wilkes will discuss practical strategies for counteracting fraud and cyberattacks by leveraging real-time streaming analytics. In his session at @ThingsExpo, Steve Wilkes, Founder and Chief Technology Officer at Striim, will provide a detailed look into leveraging streaming data management to correlate events in real time, and identify potential breaches across IoT and non-IoT systems throughout the enterprise. Strategies for processing massiv...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
The consumer IoT market is growing at an astounding rate – device ownership increased 259% from 2015 to 2016. In her session at @ThingsExpo, Noelani McGadden, Vice President of IoT at PlumChoice, will present thought-provoking insights from a recent survey, while exploring the opportunities and challenges as the market continues to grow. The data highlights which types of devices consumers currently own and are planning to purchase, the reasons why they’re purchasing these devices and their pr...
SYS-CON Events announced today that Striim will exhibit at SYS-CON's 20th International Cloud Expo® | @ThingsExpo New York, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Striim™ (pronounced “stream”) is an enterprise-grade, real-time integration and intelligence platform. Striim makes it easy to ingest high volumes of streaming data – including enterprise data via log-based change data capture – for real-time log correlation, cloud integration, edge process...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Clouber will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Clouber offers Migration as a Service (MaaS) across Private and Public Cloud (AWS, Azure, GCP) including bare metal migration to cloud. Clouber’s innovative technology allows for migration projects to be completed in minutes instead of weeks. For more updates follow #clouberio
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
SYS-CON Events announced today that Striim will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Striim is pronounced "stream", with two i's for integration and intelligence. The company was founded in 2012 as WebAction, with a mission to help companies make data useful the instant it's born. The leaders behind the Striim platform thrive on building technology companies that raise expectations for how the wor...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @ThingsExpo Silicon Valley Call for Papers is now open.
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
SYS-CON Events announced today that Outscale will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Outscale's technology makes an automated and adaptable Cloud available to businesses, supporting them in the most complex IT projects while controlling their operational aspects. You boost your IT infrastructure's reactivity, with request responses that only take a few seconds.
In his session at @ThingsExpo, Arvind Radhakrishnen will discuss how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics will be covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that CAST Highlight has been named "Bronze Sponsor" of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. CAST Highlight is an ultra-rapid code-scanning SaaS offering that identifies potential IT risks and cost savings opportunities across distributed application portfolios. By delivering data and insights on the health of portfolios, CAST Highlight provides IT leaders with objectivity and c...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, will motivate why realizing the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insigh...
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...