Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6809891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T20:08:23+00:00 2026-05-26T20:08:23+00:00

Throwing exceptions often follows the following pattern: if(condition) { throw exception; } you check

  • 0

Throwing exceptions often follows the following pattern:

if(condition) { throw exception; }

you check a condition, and if the condition is satisfied, you throw an exception. So, i was wondering if it is good idea to write a static class for it that could look like this:

public static class Throw
{
    public static void IfNullOrEmpty<T>(string @string, params object[] parameters) where T : Exception
    {
        Throw.If<T>(string.IsNullOrEmpty(@string), parameters);
    }

    public static void IfNullOrEmpty<T, I>(IEnumerable<I> enumerable, params object[] parameters) where T : Exception
    {
        Throw.If<T>(enumerable == null || enumerable.Count() == 0, parameters);
    }

    public static void IfNullOrEmpty(string @string, string argumentName)
    {
        Throw.IfNullOrEmpty(@string, argumentName, 
            string.Format("Argument '{0}' cannot be null or empty.", argumentName));
    }

    public static void IfNullOrEmpty(string @string, string argumentName, string message)
    {
        Throw.IfNullOrEmpty<ArgumentNullOrEmptyException>(@string, message, argumentName);
    }

    public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName)
    {
        Throw.IfNullOrEmpty(enumerable, argumentName, 
            string.Format("Argument '{0}' cannot be null or empty.", argumentName));
    }

    public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName, string message)
    {
        Throw.IfNullOrEmpty<ArgumentNullOrEmptyException, I>(enumerable, message, argumentName);
    }


    public static void IfNull<T>(object @object, params object[] parameters) where T : Exception
    {
        Throw.If<T>(@object == null, parameters);
    }

    public static void If<T>(bool condition, params object[] parameters) where T : Exception
    {
        if (condition) 
        {
            var types = new List<Type>();
            var args = new List<object>();
            foreach (object p in parameters ?? Enumerable.Empty<object>())
            {
                types.Add(p.GetType());
                args.Add(p);
            }

            var constructor = typeof(T).GetConstructor(types.ToArray());
            var exception = constructor.Invoke(args.ToArray()) as T;
            throw exception;
        }
    }

    public static void IfNull(object @object, string argumentName)
    {
        Throw.IfNull<ArgumentNullException>(@object, argumentName);
    }
}

(Note: The ArgumentNullOrEmptyExceptionis not defined here, but it does pretty much what one would expect.)

so instead of repeatedly writing stuff like that

void SomeFunction(string someParameter)
{
   if(string.IsNullOrEmpty(someParameter))
   {
      throw new ArgumentNullOrEmptyException("someParameter", "Argument 'someParameter' cannot be null or empty.");
   }
}

i just do

void SomeFunction(string someParameter)
{
   Throw.IfNullOrEmpty(someParameter, "someParameter"); // not .IsNullOrEmpty
}

i actually do like it, but is it also a good practice?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T20:08:24+00:00Added an answer on May 26, 2026 at 8:08 pm

    You get rid of a bit of code duplication this way (the if … throw), so in that sense it is a good idea. Just be aware that people working on the code would need to know the Throw API to be able to read and understand the code.

    One improvement could be to use expression trees to get rid of the string parameter name passing. This would improve the simplicity further, and you wouldn’t have to worry about typing the strings and keeping them correct during refactorings and such.

    For instance, on my current pet project I have this Guard class (shortened a bit):

    public static class Guard
    {
        public static void NotNullOrEmpty(Expression<Func<string>> parameterExpression)
        {
            string value = parameterExpression.Compile()();
            if (String.IsNullOrWhiteSpace(value))
            {
                string name = GetParameterName(parameterExpression);
                throw new ArgumentException("Cannot be null or empty", name);
            }
        }
    
        public static void NotNull<T>(Expression<Func<T>> parameterExpression)
            where T : class
        {
            if (null == parameterExpression.Compile()())
            {
                string name = GetParameterName(parameterExpression);
                throw new ArgumentNullException(name);
            }
        }
    
        private static string GetParameterName<T>(Expression<Func<T>> parameterExpression)
        {
            dynamic body = parameterExpression.Body;
            return body.Member.Name;
        }
    }
    

    Which I can then use like this:

    Guard.NotNull(() => someParameter);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When throwing exceptions between multiple methods, should all methods re-throw the exception? for example
I am having trouble with XMLTextWriter.WriteStartElement throwing an exception: System.InvalidOperationException when trying to write
When throwing exceptions, I often pass in a formatted string that exposes details about
Possible Duplicate: throwing exceptions out of a destructor In C++ we should never throw
Several of my overriden Equals methods have started throwing Invalid Cast Exceptions - Unable
I have some Java code that is throwing out of memory exceptions after running
What are the best practices to consider when catching exceptions and re-throwing them? I
The AbstractMavenMojo's execute method declares it throws two exceptions, MojoExecutionException and MojoFailureException. Throwing either
I try Request.Form.Set(k, v) but it's throwing exception Collection is read-only
What factors dictate throwing an exception if argument is null (eg if (a is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.