当一个未知值传递给switch语句时,应该抛出什么类型的异常 [英] What type of Exception should I throw when an unknown value is passed into a switch statement

查看:159
本文介绍了当一个未知值传递给switch语句时,应该抛出什么类型的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新以使枚举不是方法的参数...

Updated to make the enum not an argument to the method...

这种类型的问题在switch语句中出现了很多枚举。在示例代码中,开发人员已经计入了程序正在使用的所有国家,但如果将另一个国家添加到Country枚举中,则应抛出异常。我的问题是,应该抛出什么类型的异常?

This type of problem comes up a lot with enums in switch statements. In the example code, the developer has accounted for all countries the program is currently using, but if another country is added to the Country enum, an exception should be thrown. My question is, what type of exception should be thrown?

enum Country
{
    UnitedStates, Mexico,
}

public string GetCallingCode(Guid countryId){
    var country = GetCountry(countryId);
    switch (country)
    {
        case Country.UnitedStates:
            return "1";
            break;
        case Country.Mexico:
            return "52";
            break;
        default:
            // What to throw here
        break;
    }
}

我看过


  • 未实现在请求的方法或操作未实现时抛出的异常。

  • NotSupported 基类中不支持这些方法,期望这些方法将被实现在派生类中。派生类可能仅实现基类中的一部分方法,并为不支持的方法抛出NotSupportedException。

    对于有时可能对象执行请求的操作的情况,以及对象状态确定是否可以执行操作,请参阅InvalidOperationException。

  • em =nofollow> InvalidOperation

  • NotImplemented, The exception that is thrown when a requested method or operation is not implemented.
  • NotSupported There are methods that are not supported in the base class, with the expectation that these methods will be implemented in the derived classes instead. The derived class might implement only a subset of the methods from the base class, and throw NotSupportedException for the unsupported methods.
    For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.
  • InvalidOperation is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.

我的猜测是NotImplemented或Invalid Operation。我应该使用哪一个?有人有一个更好的选择(我知道滚动你自己总是一个选项)

My guess is either NotImplemented or Invalid Operation. Which one should I use? Does someone have a better option (I know rolling your own is always an option)

推荐答案

我将与 ArgumentException 一起进行,因为agrument无效。

I would go with ArgumentException, as the agrument is invalid.

编辑: http://msdn.microsoft.com/en-us/library/system。 argumentexception%28v = vs.71%29.aspx

还有 InvalidEnumArgumentException ,这可能更准确地描述问题,但是,我以前没有看到任何人使用过。

There is also InvalidEnumArgumentException, which might more accurately describe the problem, however, I have not seen anyone use it before.

这篇关于当一个未知值传递给switch语句时,应该抛出什么类型的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆