Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I design a function that validates input and reports a useful error?

Quick answer

Write down what each parameter may contain, check those conditions before doing the main work, and throw an exception that matches the violation. In C#, use a specific exception such as ArgumentNullException for null or ArgumentOutOfRangeException for a value outside an allowed range. Include a clear reason and identify the parameter, so callers can understand what to fix. The example assumes a repeat count from 1 through 10.

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

How should I start designing a function that validates its input? I want the error to explain the problem rather than just say something went wrong.

Geez

Start by writing the function’s input contract: what values are allowed, and what should happen when a value breaks that rule? Then check the contract before the function does its main work. For a C# method, Microsoft recommends throwing an exception when an argument is invalid and prevents the method from doing its defined job. Choose the most specific applicable exception; its message should explain the reason, and ParamName can identify the argument. [S1]

For example, assume a function repeats a message and accepts a count from 1 through 10. Its contract is: the message cannot be null, and the count must be in that inclusive range. This example allows an empty string, since the stated contract does not forbid one. Being explicit about boundaries—such as whether zero is allowed—helps make the check and its error message agree.

Follow-up question

What would that look like as a small C# function, including a helpful message?

Geez

Here is one implementation. It checks both arguments before building the result:

using System;
using System.Linq;

static string RepeatMessage(string message, int count)
{
    if (message is null)
        throw new ArgumentNullException(
            nameof(message), "Message cannot be null.");

    if (count < 1 || count > 10)
        throw new ArgumentOutOfRangeException(
            nameof(count), count,
            "Count must be between 1 and 10 inclusive.");

    return string.Join(" ", Enumerable.Repeat(message, count));
}

ArgumentNullException makes the null case explicit; ArgumentOutOfRangeException fits a number outside the allowed range. The exception identifies the parameter, and its message says what rule was broken. .NET guidance recommends ArgumentException when an argument fails its specification and points to these more specific types when suitable. [S2]

Follow-up question

How do I make sure the message is useful to whoever calls the function, not just to me?

Geez

Name the offending parameter and state the expected condition in ordinary language. “Count must be between 1 and 10 inclusive” tells the caller the accepted range; “Invalid input” does not. The .NET API guidance says a custom ArgumentException message should meaningfully describe the invalid argument and expected range, and that ParamName identifies the argument. [S2]

Avoid putting a guessed correction or unrelated implementation detail in the message. Describe the contract violation rather than guessing why the caller supplied that value. Keep the message consistent with the check: if the allowed range changes, update both the validation and its explanation.

Follow-up question

What pattern can I reuse when I add validation to another function?

Geez

Use this sequence: define the allowed input, check each condition early, choose the most specific suitable exception, and state the parameter and rule. Then put the main operation after the checks. For this example, RepeatMessage("Hi", 3) returns Hi Hi Hi; RepeatMessage("Hi", 0) throws because zero violates the assumed count range. These are illustrations of the contract, not claims about executed tests.

The example is C#/.NET-specific; its exception types are not a universal pattern for every language. The cited guidance supports .NET argument validation, but does not establish which exceptions or wording are right in another language or for a different function contract. Check the conventions for your language before transferring the pattern.

A practical checklist

  • Write down allowed values for each parameter, including boundary values.

  • Check invalid inputs before performing the function’s main work.

  • Choose the most specific suitable exception for each violation.

  • Identify the offending parameter and explain the violated rule.

  • Keep the validation and its error message aligned when the contract changes.

A few more useful answers

Can I use this exact exception pattern in another programming language?

Not necessarily. These exception recommendations are specific to C# and .NET. Use the target language’s conventions and exception types for its input-validation contract.

When should I use ArgumentOutOfRangeException?

Use it when an argument is outside the range allowed by the function’s contract. For a null argument, a more specific option is ArgumentNullException. [S2]

Sources

References used for this guide.

  1. [S1] Create and Throw Exceptions — C#
    learn.microsoft.com · Checked
  2. [S2] ArgumentException Class — .NET API reference
    learn.microsoft.com · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work