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.