Welcome!

Microsoft Cloud Authors: David H Deans, Yeshim Deniz, Janakiram MSV, 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.

Conclusion
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
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
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. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
SYS-CON Events announced today that CAST Software 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed 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 were 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 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...
SYS-CON Events announced today that Pulzze Systems will exhibit at 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. Pulzze Systems Inc, provides the software product "The Interactor" that uniquely simplifies building IoT, Web and Smart Enterprise Solutions. It is a Silicon Valley startup funded by US government agencies, NSF and DHS to bring innovative solutions to market.
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
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, will introduce 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...
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 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...
SYS-CON Events announced today that Elastifile 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. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...