.NET 8 Exception helpers

Throwing exceptions is becoming much easier in .NET 8

Home DailyDrop

Daily Knowledge Drop

A number of helper methods are being introduced with .NET 8, which make the process of checking values and throwing exception a lot simpler.

Keep in mind .NET 8 is in pre-release, so the functionality could potentially change or be removed before the final .NET8 release.


Existing helper

An example of an existing (prior to .NET 8) exception helper method, is the ArgumentException.ThrowIfNullOrEmpty method.

Instead of having to do this:

void ManualThrowException(string strParam)
{
    if (string.IsNullOrEmpty(strParam))
    {
        throw new Exception($"{nameof(strParam)} is null or empty");
    }
}

The ThrowIfNullOrEmpty method can be used, which checks the value of the parameter and throws the exception:

void ThrowNullOrEmptyException(string strParam)
{
    ArgumentException.ThrowIfNullOrEmpty(strParam);
}

New helpers

There are a number of new static helper methods (on ArgumentOutOfRangeException) being introduced, which include:

  • ThrowIfZero
  • ThrowIfNegative
  • ThrowIfNegativeOrZero
  • ThrowIfGreaterThan

The usage and functionality of these are the same as ThrowIfNullOrEmpty - the parameter is checked, and an exception is throw if the check fails.

To check if a int value is zero or negative, instead of this:

void ManualThrowZeroNegativeException(int intParam)
{
    if (intParam <= 0)
    {
        throw new Exception($"{nameof(intParam)} is less than or equal to zero");
    }
}

This can be done:

void EnhancedThrowZeroNegativeException(int intParam)
{
    ArgumentOutOfRangeException.ThrowIfNegative(intParam);
}

If thrown, the exception generated is also more informative than before, including the parameter name in the exception text:

'intParam' must be a non-negative value.

The result - more readable code, and quicker and easier for a developer to thrown an exception.


Notes

A relatively small and simple helper method update - but one will facilitate cleaner, simpler and more readable code.


References

New ArgumentException and ArgumentOutOfRangeException helpers in .NET 8

Daily Drop 225: 02-01-2023

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net .net8 exception helpers