Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

INETA's Topic Choice: How to Handle Exceptions with Class

Defining custom exceptions

By now most of you reading this article will be familiar with .NET exception handling, at least in its basic form. You know how to catch exceptions using Try...Catch blocks. You know how to handle exceptions raised by the framework. You may even have created and thrown your own exceptions.

In this article you'll learn how to take this to the next level - how to define custom exceptions for your own classes and components, and the design patterns that you should use when doing so.

I have included two sample projects to help explain these design patterns. The SampleComponent project contains the MyComponent component, which raises a variety of exceptions. The project also includes a couple of custom exception classes that you'll learn about later in this article. The component represents any generic component or reusable class.

If you have no interest in components or code reuse, you really don't need to read this article - just keep throwing System.Exception objects (you have more important things to learn than what I have to say here).

The SampleComponentTest project represents a generic client application that uses a component.

The ApplicationException Class
It all begins with the following remark in Microsoft's documentation for the System.ApplicationException class:

ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.

As is often the case with Microsoft documentation, a short paragraph has far-reaching implications that tend to be a bit on the obscure side. Consider what this paragraph implies:

  1. You should avoid throwing system exceptions.
  2. If you create custom exceptions, they should derive from ApplicationException.
  3. There is reason to differentiate between exceptions thrown by the system and those thrown by the framework.
This implies that you should never use the following code, found in the MyComponent class:

    Public Function SimpleTest1()
      As String
        Throw New Exception ("Here is an exception in SimpleTest1")
End Function

Perhaps the solution then is to use code like this:

Public Function SimpleTest2() 
    As String
    Throw New ApplicationException( _
    "Here is an exception in SimpleTest2")
End Function

This is acceptable but still not perfect. The ApplicationException documentation also remarks:

In most scenarios, instances of this class should not be thrown. In cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.

It's apparent that Microsoft's intent is that developers create their own custom exceptions. But why?

Custom Exceptions and Classes
Think of the .NET Framework itself as your guide. What is the framework if not a set of reusable classes? How does Microsoft raise exceptions in the framework? They don't raise generic System. Exception objects. If you look at the documentation for the various classes in the framework, you'll see that each one documents the exceptions that it might raise. Namespaces define custom exceptions used by classes in that namespace. For example, classes in the System.IO namespace often raise System.IOException errors.

Why use this approach? Obviously, it allows for more flexible error handling, such as that shown in the ExceptionButtons_ Click method of the SampleComponentTest project (see Listing 1).

As you can see, you can build a list of Catch terms to provide handling according to the exception type. Most developers are familiar with this approach - but there's another for use with custom exceptions.

When you design a class or component, it is important to define the exceptions that it can raise. But you can't just allow framework exceptions to propagate outward from your component; you might change something in your code, or Microsoft might change a framework class in such a way that your component will end up raising exceptions that are not part of your original definition.

Instead, you should catch all errors that might occur in your component and throw your own custom error for the class. By the way, that's what the InnerExcep-tion property of the System.Ex-ception class is for. When you throw your custom exception, you set the inner exception to the originating exception so clients of your component or class can obtain information about the original cause of the problem.

Creating Custom Exceptions
The MyExceptionType1 class (see Listing 2) demonstrates how you might create your own class that derives from ApplicationException. The class also extends the base class by capturing additional information - in this case an ExceptionType enumeration that describes the cause of the exception.

MyExceptionType1 is a workable class, but if you're designing a component for reuse you should follow Microsoft's example just a bit further and provide for localization.

MyExceptionType2 (see Listing 3) demonstrates a number of interesting features. The Errors.resx file contains the “localized” strings. This file is embedded in the component, and represents the default (neutral) strings. You can add satellite assemblies to the component for different locales - even distributing them after the fact to add additional language support. The exception class caches the resource manager, loading it only on first use, then holding a reference for future use. Access to the resource manager is synchronized on an object in order to make sure that the exceptions will work correctly with multithreaded clients.

In this example, if the string does not match a key in the resource file, the original string is considered the message. This is arguably an error condition, but since the whole point is to throw the original exception, it makes little sense to throw a missing resource exception instead. However, you might want to report this condition to the debugger to help track down missing strings.

The MyExceptionType2 class also provides constructors that allow you to incorporate parameters into the localized string and to report inner exceptions.

The class is also marked as serializable. This makes it possible for exceptions to be passed as parameters and return values on remote components. If you do plan to use it with remote components, consider placing your exception classes in their own assembly to make it easy to support them on both the server and client sides.

The SampleComponent and SampleComponentTest projects demonstrate the raising and catching of various exceptions. The design patterns shown here are very similar to those that Microsoft uses within the .NET Framework.

It may seem like a lot of extra effort, but it really isn't. In fact, the samples contain most of the code you'll need. And the extra effort to properly design the exception side of your object model will pay off in the long run in terms of long-term stability and reliability - and will save you a great deal of effort should you decide at a later date to localize your components or classes.

More Stories By Dan Appleman

Daniel Appleman is president of Desaware, Inc., a developer of add-on products and components for Microsoft Visual Studio. He is a cofounder of Apress, and the author of numerous books, including Moving to VB.NET: Strategies, Concepts and Code; How Computer Programming Works; Dan Appleman's Visual Basic Programmer's Guide to the Win32 API; Always Use Protection: A Teen's Guide to Safe Computing, and a series of e-books on various technology and security topics. (A complete list can be found at www.desaware.com.)

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
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 Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...