Skip to content

[API Proposal]: More helper methods for exception types #69637

@hrrrrustic

Description

@hrrrrustic

Background and motivation

A few more helper methods that can replace a lot of boring and copy-paste if checks in dotnet/runtime and user code as well.
I believe that this one and #69590 will cover all possible helpers 😸

API Proposal

public class FileNotFoundException
{
    public static void ThrowIfNotExists([NotNull] string? path) {}
}

public class DirectoryNotFoundException
{
    public static void ThrowIfNotExists([NotNull] string? path) {}
}

public class NotSupportedException
{
    public static void ThrowIf(bool condition, string? message = null) {}
}

public class InvalidOperationException
{
   public static void ThrowIf(bool condition, string? message = null) {}
}

API Usage

FileNotFoundException

if (!File.Exists(fileName))
{
throw new FileNotFoundException(fileName);
}

I also saw weird code like this

public void SomeIORelatedMethod(string path)
{
    if (!new FileInfo(path).Exists)
        throw new FileNotFoundException();
}

DirectoryNotFoundException exactly same as previous, File.Exists -> Directory.Exists, new FileInfo -> new DirectoryInfo

NotSupportedException

get
{
if (!CanSeek)
throw new NotSupportedException(SR.SeekNotSupported);
return _stream.Length;
}

There are 15 more absolutely same checks only in this file. Widely used in Stream and Http related classes

InvalidOperationException
I think the only Enumerator types in /runtime have more than thousand lines of code like this

if (_index == 0 || _index == _list._size + 1)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions