检查可能的异常与在 try catch 中包装代码

本文关键字:catch try 包装 代码 异常 检查 | 更新日期: 2023-09-27 18:34:38

我正在检查方法中的无效条件:

public void DoStuff()
{
    int result;
    if (DeviceSettings == null)
        throw new NullReferenceException("Not initialized");
    if (!Serial.IsNotEmpty())
        throw new Exception("The serial number is empty.");
    if (!int.TryParse(Serial, out result))
        throw new ArgumentOutOfRangeException(Serial);
    //do stuff
}

代码对我来说看起来很尴尬。是否有更标准的方法来实现逻辑来验证没有无效条件

检查可能的异常与在 try catch 中包装代码

我喜欢将

抛出异常限制在真正"特殊"的情况下。 对于上面这样的东西,我会有一个从 DoStuff(( 返回的"响应"类型的数据结构,而不是一个 void,其中可能包含验证错误列表。

class Response()
{
     public List<string> errors {get;set;}
}
public Response DoStuff()
{
    var response = new Response();
    int result;
    if (DeviceSettings == null)
        response.errors.Add("Not Initialized");
    if (!Serial.IsNotEmpty())
        response.errors.Add("The serial number is empty.");
    if (!int.TryParse(Serial, out result))
        response.errors.Add("Argument out of range");
    // check your response errors, return if necessary
    //do stuff
    return response;
}

这样,在数据验证错误的情况下,您将获得所有可能的错误,而不仅仅是第一个错误。