Click here to Skip to main content
15,892,059 members
Articles / Programming Languages / C#
Tip/Trick

Write thoughtful code, write meaningful code, become a legend: Throwing exceptions

Rate me:
Please Sign up or sign in to vote.
4.39/5 (9 votes)
25 Aug 2015CPOL2 min read 16.6K   11   7
General thoughts and tips on throwing exceptions.

Introduction

Exceptions play an important role in a well designed and maintainable piece of code. One of the primary reasons for their existence is mainly out of declarative reasons and in order to manifest clarity. Before there were exceptions, for decades developers poisoned deep-nested-if-then-else-code-blocks by injecting additional control flow for error checking and handling. They wrote functions that did not return the result of the single task they were meant to accomplish, but instead returned a dubious integer coded error state that was then also hardwired into the jungle of predicates.

This not only lead to severe cases of hair loss, digestion disorders and aggressive behavior among the developers, but as a direct result produced tons of obfuscated legacy code that costs the industry billions each year and still does. Malicious gossip has it that this may also secure a lot of jobs. Be that as it may:

A good developer always throws an exception if a check of a critical precondition fails and before the poisoned blood reaches the very heart of the algorithm. In other less poetic words: Sh!% in and even more sh!% will come out of it.

Secondly, but even more important for creating maintainable code, exceptions provide a powerful tool to enhance the declarative flow of your code. A thoughtful placement of an exception elegantly fits into good structured code and renders additional code comments redundant. If used consequently this greatly helps the maintainer to understand your thoughts while not distracting him or her from the job of understanding or even purifying your work.

At the end and because I am a practitioner. I want to supply you with some extension methods that I tend to use often when throwing exceptions. Even though extension methods can also lead to evil obfuscation of code, I think they can be quite a nice tool in this area. Enjoy!

Using the code

Consider the following code snippet which makes use of the extension methods below:

C#
public abstract class StateMachineBase<TStateEnum> : IStateMachine<TStateEnum> where TStateEnum : struct
{
	static StateMachineBase ()
    {
    	typeof(TStateEnum).IsEnum.NoThenThrow<ArgumentException>("The type parameter must be of type: {0}", typeof(Enum));
	}
...

public static class ExceptionExtensionsMethods
{
	[DebuggerStepThrough]
	public static void YesThenThrow<T>(this bool predicate, string message, params object[] messageArguments) where T : Exception
	{
	  	if (predicate)
	  	{
	    	var exception = String.IsNullOrEmpty(message) 
	    		? (T) Activator.CreateInstance(typeof (T), true)
	    		: (T) Activator.CreateInstance(typeof (T), String.Format(message, messageArguments));

	    	throw exception;
	  	}
	}

	[DebuggerStepThrough]
	public static void NoThenThrow<T>(this bool predicate, string message, params object[] messageArguments) where T : Exception
	{
	  	if (predicate == false)
	  	{
	    	var exception = String.IsNullOrEmpty(message) 
	    		? (T) Activator.CreateInstance(typeof (T), true)
	    		: (T) Activator.CreateInstance(typeof (T), String.Format(message, messageArguments));

	    	throw exception;
	  	}
	}
}

Points of Interest

Please be aware that while the extension methods provide a declarative way of throwing an exception, you pay the cost of one additional frame in the resulting stack trace.

History

1.0 Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Germany Germany
I am a passionate software architect and team leader with the strong need to work hands on for many more years to come. Understanding and combining the work of others into a great product is my everyday bread and butter.

Comments and Discussions

 
QuestionControl flow? Pin
DaveBlack26-Aug-15 10:50
DaveBlack26-Aug-15 10:50 
AnswerRe: Control flow? Pin
Philipp Paetzold18-Oct-15 6:07
professionalPhilipp Paetzold18-Oct-15 6:07 
QuestionWhy it has to be so complicated? Pin
Aurimas26-Aug-15 3:10
Aurimas26-Aug-15 3:10 
AnswerRe: Why it has to be so complicated? Pin
Philipp Paetzold26-Aug-15 5:06
professionalPhilipp Paetzold26-Aug-15 5:06 
Questionyes/no versus true/false? Pin
ignatandrei26-Aug-15 1:45
professionalignatandrei26-Aug-15 1:45 
yes/no versus true/false?
GeneralNice idea Pin
wmjordan25-Aug-15 22:37
professionalwmjordan25-Aug-15 22:37 
GeneralRe: Nice idea Pin
Philipp Paetzold25-Aug-15 23:19
professionalPhilipp Paetzold25-Aug-15 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.