我在此代码中收到此错误
public static AbilityScore GetAbilityScore(AbilitiesSort abilitySort, int score)
{
var abilityScores = AbilitiesScore[abilitySort];
foreach (var abilityScore in abilityScores)
if (abilityScore.Min <= score && abilityScore.Max >= score)
return abilityScore;
throw new System.Exception(); // error in this line
}
我在这一行throw new System.Exception();
答案 0 :(得分:1)
这只是意味着它找不到任何与得分匹配的能力分数。
所以,它执行
throw new System.Exception();
你需要考虑如何处理这种情况。抛出异常并在调用GetAbilityScore时捕获它,或返回null(假设AbilityScore是引用类型)。
如果您坚持使用异常策略,请不要抛出System.Exception
。
相反,从System.Exception
派生自定义例外。
请阅读Choosing the Right Type of Exception to Throw
答案 1 :(得分:0)
在最后执行代码的其他部分之后,你总是抛出异常,似乎if (abilityScore.Min <= score && abilityScore.Max >= score)
函数中的if条件foreach
失效并未返回并执行throw new System.Exception();
抛出异常,所以检查条件是否总是假的。同样在你的foreach中你是在条件而不是其他情况下返回,所以在其他情况下也会返回
你可以在try catch块中包装你的代码,这样当异常发生抛出异常时,在其他情况下不是
try
{
var abilityScores = AbilitiesScore[abilitySort];
foreach (var abilityScore in abilityScores)
{
if (abilityScore.Min <= score && abilityScore.Max >= score)
{
return abilityScore;
}
else
{
return null
}
}
}
catch
{
throw new System.Exception();
return null;
}
或者你可以返回null而不抛出任何异常
try
{
var abilityScores = AbilitiesScore[abilitySort];
foreach (var abilityScore in abilityScores)
{
if (abilityScore.Min <= score && abilityScore.Max >= score)
{
return abilityScore;
}
else
{
return null
}
}
}
catch
{
return null;
}
答案 2 :(得分:0)
不幸的是,Mostafiz的答案在第一次找不到正确的能力后失败了,如果列表中的第一项不匹配,则返回null。为避免这种情况,您可以尝试以下任何一种方法,具体取决于最适合您的方法。
// Use this if you're using C# 6.0
public static AbilityScore GetAbilityScore(AbilitiesSort abilitySort, int score)
{
return AbilitiesScore[abilitySort]?.FirstOrDefault(s => s.Min <= score && s.Max >= score);
}
// otherwise you can try this
public static AbilityScore GetAbilityScore(AbilitiesSort abilitySort, int score)
{
var scores = AbilitiesScore[abilitySort];
if (scores == null) throw new NullReferenceException("Target ability scores could not be found.");
return scores.FirstOrDefault(s => s.Min <= score && s.Max >= score);
}
// And lastly, if linq does not work for you
public static AbilityScore GetAbilityScore(AbilitiesSort abilitySort, int score)
{
var scores = AbilitiesScore[abilitySort];
if (scores == null) throw new NullReferenceException("Target ability scores could not be found.");
foreach (var abilityScore in scores)
if (abilityScore.Min <= score && abilityScore.Max >= score)
return abilityScore;
return null;
}
最后,我仍然建议你对使用此方法返回的AbilityScore进行空检查
var myAbilityScore = className.GetAbilityScore(abilitySort, score);
if (myAbilityScore != null) {
// code goes here...
}
答案 3 :(得分:-2)
也许这就是你应该做的。目前,如果出现问题,它只会显示异常时会抛出异常。
public static AbilityScore GetAbilityScore(AbilitiesSort abilitySort, int score)
{
try {
var abilityScores = AbilitiesScore[abilitySort];
foreach (var abilityScore in abilityScores)
if (abilityScore.Min <= score && abilityScore.Max >= score)
return abilityScore;
}
catch {
throw new System.Exception();
}
}
这样,只有在第一部分无法执行时才会抛出错误。