调用一个不打算调用的函数时是否会抛出系统异常?

时间:2021-01-05 18:22:34

Let's put that I have an mutable object that has a function that mutates it, and that function should not be called under certain circumstances. How should I react to code calling a function under those circumstances?

让我们说我有一个可变对象,它有一个改变它的函数,并且在某些情况下不应该调用该函数。在这种情况下,我应该如何响应调用函数的代码?

For example:

  • Object: Combat
  • Function: PlayRound()
  • Circumstance: The Combat has already a Winner
  • 情况:战斗已经获胜

  • Consecuence: Combat would end in an inconsistent state
  • 结果:战斗将以不一致的状态结束

I can think of two ways of acting, neither of which find suficient:

我可以想到两种表现方式,两种方式都不合适:

  1. Return a magic value, null for example. This has the problem that it does not follow the Fail Faster ideology, and keeps the program in an invalid state.

    返回一个魔术值,例如null。这有一个问题,它不遵循Fail Faster意识形态,并使程序保持无效状态。

  2. Throw an exception. This is the one that I find more suitable, but I'd like to avoid creating a new Exception if it already exists one that fulfills that role.

    抛出一个例外。这是我觉得更适合的那个,但我想避免创建一个新的Exception,如果它已经存在一个满足该角色的那个。

For the second case, I could throw something like ArgumentInvalidException but I can't find the equivalent for this case.

对于第二种情况,我可以抛出像ArgumentInvalidException这样的东西,但我找不到这种情况的等价物。

There is an equivalent existing Exception for this scenario?

此方案存在等效的现有异常?

Note: Let's assume that the function is documented, and it says explicitly that the function should never be called under those circumstances. Still I think it should fail hard if the developer fails to read the documentation =)

注意:假设函数已记录在案,并明确说明在这些情况下永远不应该调用该函数。我认为如果开发人员无法阅读文档,它应该会失败=)

1 个解决方案

#1


I'd define an application exception specific to that. But you could use InvalidOperationException here sanely.

我将定义一个特定于此的应用程序异常。但是你可以在这里使用InvalidOperationException。

#1


I'd define an application exception specific to that. But you could use InvalidOperationException here sanely.

我将定义一个特定于此的应用程序异常。但是你可以在这里使用InvalidOperationException。