开发者

Getting an Exception from an Enum

开发者 https://www.devze.com 2023-04-01 07:01 出处:网络
I have received an error log that shows the following code threw the exception in set public double Value {

I have received an error log that shows the following code threw the exception in set

  public double Value {
        get {
            switch (DefinedUnits.Distance) {
                case DistanceUnits.Feet:开发者_开发问答 { return Feet; }
                case DistanceUnits.Meters: { return Meters; }
                case DistanceUnits.NM: { return NauticalMiles; }
                default: { throw new Exception("Invalid Distance Unit Specified"); }
            }
        }
        set {
            switch (DefinedUnits.Distance) {
                case DistanceUnits.Feet: { Feet = value; break; }
                case DistanceUnits.Meters: { Meters = value; break; }
                case DistanceUnits.NM: { NauticalMiles = value; break; }
                default: { throw new Exception("Invalid Distance Unit Specified"); }
            }
        }
    }

DefinedUnits.Distance is an enum:

public enum DistanceUnits {
        Meters,
        Feet,
        NM
    }

There is no way I can see in my code that something else can be sent. I have no place where this enum is treated as an integer so that a bad value could be passed in. The user cannot tell me what he was doing. Or rather he tells me he was doing something that could not have called this.

Is there a logical explanation for why this happened and how can I stop it?

Thanks


Perhaps the value was fetched before it was ever set, leaving a default value which was invalid? (Admittedly if you haven't set any corresponding integers, Meters should correspond to 0...) You should adjust your code to:

  • Throw a more specific exception (e.g. InvalidOperationException)
  • Include the value in the exception message

If you have the stack trace, you should at least be able to see whether it was the getter or the setter that was throwing the exception...


DefinedUnits.Distance is either null or initialised to something out of range.

Changing your default handler should give you a clue:

default: { throw new Exception("Invalid Distance Unit Specified: " + DefinedUnits.Distance != null ? DefinedUnits.Distance.ToString() : '**null**' ); }


Print to the log Exception.StackTrace and (int)DefinedUnits.Distance value to get more information.


If you use Dotfuscator (or some other obfuscating software) and you convert string value (for instance "Feet") to enum, then it is possible that enum names were obfuscated and string-to-enum conversion fails.

0

精彩评论

暂无评论...
验证码 换一张
取 消