Skip to main content
 首页 » 编程设计

c#之当缺少 ArgumentNullException 参数名称

2024年02月13日22zhujiabin

在我的应用程序中,有几次 ArgumentNullException 被抛出,但没有提供任何参数名称。这只发生在生产环境中(在脚本服务中抛出异常,由 javascript 调用)。 我试图在 StackTrace 指向的代码片段中重现此类错误,但我能够重现的每个 ArgumentNullException 都在其消息中包含了一些参数名称。

所以,我的问题是有人知道什么时候抛出 ArgumentNullException 而没有提供参数名称吗?或者什么方法最终会触发这个异常?



脚本服务是关于从应用程序缓存中获取一些信息:

private Dictionary<int, MyType> CachedDictionary 
{ 
    get 
    { 
        //return the Item from the application cache 
        return GetItem() as Dictionary<int, MyType>; 
    } 
    set 
    { 
        //adds the Item to the application cache  
        //with sliding expiration of X minutes 
        AddItem(value); 
    } 
} 
 
public List<MyType> Get(List<int> idsToRead) 
{ 
    List<int> idsNotCached = idsToRead.Except<int>(CachedDictionary.Keys.ToList<int>()).ToList<int>(); 
    if (idsNotCached.Count > 0) 
    { 
        //Exception stack trace points to next line: 
        MyTypeCollection DBitems = BusinessLayer.StaticLoadFromDB(idsNotCached);  
        lock (CachedDictionary) 
        { 
            foreach (MyType item in DBitems) 
                if (!CachedDictionary.ContainsKey(item.ID)) 
                    CachedDictionary.Add(item.ID, item); 
        } 
    } 
    return CachedDictionary.Where(p => idsToRead.Contains(p.Key)).Select(p => p.Value).ToList<MyType>(); 
} 
 
 
public static MyTypeCollection StaticLoadFromDB(List<int> ids) 
{ 
    try 
    { 
        //load from db... 
    } 
    catch (Exception e) 
    { 
        return HandleException<MyType>(e); 
        //returns MyTypeCollection with HasError set to TRUE and defined ErrorMessage 
    } 
} 

请您参考如下方法:

没有代码很难确定可能的原因。您可以尝试以下一般准则来尝试找出问题。

异常 ArgumentNullException 通常在未提供方法参数时触发。 ArgumentNullException 的构造函数不需要提供参数名称。有些方法只接受一个参数,因此无需提供为 null 的参数名称。

异常可以在代码中的任何一点触发,只需简单地

throw new ArgumentNullException(); 

为了帮助确定问题的位置和原因,您需要查看堆栈跟踪,然后查看提供的参数。尝试确定进程当时试图做什么,从而确定可能的参数值。

或者,您可以尝试添加一个 try catch,记录调用方法时发送到该方法的可能值。例如,

try 
{ 
    FunctionThatThrowsArgumentNullException(myParameter); 
} catch (ArgumentNullException ane) 
{ 
    Log.WriteLine("Argument Null Exception Raised", ane); 
    Log.WriteLine("Parameters supplied : {0}", myParameter); 
    throw; // Pass the exception on, as we are only logging 
}