Skip to content

TypeConverter Error Handling #15

@BenMendel

Description

@BenMendel

I wrote this uint TypeConverter:

internal sealed class HexUIntConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
        => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

    public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
    {
        if (value is not string str)
            return base.ConvertFrom(context, culture, value);

        culture ??= CultureInfo.CurrentCulture;

        if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
        {
            if (uint.TryParse(str[2..], NumberStyles.HexNumber, culture, out var hex))
            {
                return hex;
            }

            ThrowHelper.ThrowNotSupportedException($"Invalid hex uint: '{str}'.");
        }

        if (uint.TryParse(str, NumberStyles.Integer, culture, out var dec))
        {
            return dec;
        }


        throw new InvalidOperationException($"HexUIntConverter cannot convert '{str}' to uint.");
        throw new FormatException($"HexUIntConverter cannot convert '{str}' to uint.");
        return ThrowHelper.ThrowInvalidOperationException<object?>($"HexUIntConverter cannot convert '{str}' to uint.");
    }
}

As suggested in Type Converter Page, I tried throwing InvalidOperationException,
Then tried as suggested in Using Custom Type Converter, I tried throwing FormatException
Both resulted in: Error: Failed to convert '4294967296' to Nullable'1. and not with my custom exception message.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions