Click here to Skip to main content
12,883,272 members (38,867 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked
Posted 22 Apr 2013

Intrinsic String.Format in Exception Throwing

, 22 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
A handy way to raise an exception without having to call String.Format for the exception message


This little tip or code snippet provides a handy way to raise an exception without having to call String.Format for the exception message.


I am writing a service which imports files, does calculations, and exports on to an HTTP API. I ended up doing a lot of what I've always disliked doing, and that is always having to use string format to build the message parameter for the throw calls.

Using the Code

The code looks like this:

private void ThrowException<T>(string message, params object[] values) where T : Exception, new()
    // NOTE Cannot provide arguments when creating an instance of a type parameter T.
    var exception = (T)Activator.CreateInstance(typeof(T), string.Format(message, values));
    throw exception;

And you would simply use it like this:

ThrowException<InvalidOperationException>("VehicleMovementBatch Id {0} was not located.", batchId);  

Points of Interest

I found it quite interesting that I can't instantiate a type parameter with parameters, e.g. var x = new T("Hello") is not allowed by the compiler, even if a constructor for T has a string parameter, I had to go work around that and use CreateInstance.

Nearly all of the exceptions I am raising are brand new, i.e., they are not based on another caught exception, so I haven't allowed for an innerException parameter. That would be very easy to add, but remember to make it optional.


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


About the Author

Brady Kelly
Founder Erisia Web Development
South Africa South Africa
I am a software developer in Johannesburg, South Africa. I specialise in C# and ASP.NET MVC, with SQL Server, with special fondness for MVC and jQuery. I have been in this business for about eighteen years, and am currently trying to master Angular 2 and .NET Core, and somehow find a way to strengthen my creative faculties.
- Follow me on Twitter at @bradykelly

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170422.1 | Last Updated 23 Apr 2013
Article Copyright 2013 by Brady Kelly
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid