Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thoughts on throw helpers

To reduce redundant code, I have some throw helper methods:

protected static X ThrowInvalidOperation(string operation, X a, X b) {
    throw new InvalidOperationException("Invalid operation: " + a.type.ToString() + " " + operation + " " + b.type.ToString());
}

Usage:

    public static X operator +(X a, X b) {
        if (...) {
            return new X(...);
        }
        return ThrowInvalidOperation("+", a, b);
    }

Problem: Because the operator + must always return a value, I fixed this by making ThrowInvalidOperation return a value and call it with returnThrowInvalidOperation("+", a, b);

There a many disadvatages - one is because I can't call it from a method returning a different type.
I wish there is there a way to mark the helper function "always throws a exception", so the compiler stops tracking return values.

Q: What possibilities do I have to make this work?

like image 461
joe Avatar asked Nov 25 '13 11:11

joe


1 Answers

Make the exception:

protected static Exception MakeInvalidOperation(string operation, X a, X b)
{
    return new InvalidOperationException(
        "Invalid operation: " + a.type + " " + operation + " " + b.type);
}

Then throw it:

throw MakeInvalidOperation("+", a, b);

You're in good company:

// Type: Microsoft.Internal.Web.Utils.ExceptionHelper
// Assembly: WebMatrix.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: 3F332B40-45DB-42E2-A4ED-0826DE223A79
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WebMatrix.Data\v4.0_1.0.0.0__31bf3856ad364e35\WebMatrix.Data.dll

using System;

namespace Microsoft.Internal.Web.Utils
{
    internal static class ExceptionHelper
    {
        internal static ArgumentException CreateArgumentNullOrEmptyException(string paramName)
        {
            return new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, paramName);
        }
    }
}

Although it's not that much code to write your own custom Exception-based type (or InvalidOperationException-based) and define some constructor that formats a message for you.

To reduce redundant code

When I hear this, I think AOP which is implemented quite well by PostSharp. If you have lots of redundant code you should consider AOP, but bear in mind that it might be overkill.

like image 128
ta.speot.is Avatar answered Oct 20 '22 12:10

ta.speot.is