在Code中,如下所示:
假设我有try
,其上有一堆单独的行,第一行失败,
在我的catch块中我可以输出失败,有没有办法继续try块中的下一个语句?
try
{
string owner = props["primary site owner"].ToString();
string owneremail = props["primary site owner Email"].ToString();
... 10 more statements like the above, mapping properties to variables
}
catch (Exception e)
{
Console.WriteLine("error");
}
例如,如果它未能设置所有者,我可以在catch块中发出resume
命令,让它尝试下一步设置owneremail吗?
基本上我想在下面这个行为,但不要10个不同的try catch块。
try
{
string owner = props["primary site owner"].ToString();
}
catch (Exception e)
{
Console.WriteLine("error with site owner");
}
try
{
string owneremail = props["primary site owner Email"].ToString();
}
catch (Exception e)
{
Console.WriteLine("error with email");
}
... 10 more try catch blocks ...
答案 0 :(得分:6)
使用try-catch块进行程序流程不是最佳做法,不应该使用。
此外,您不应该依赖于捕获可以先检查并正确处理的错误。
因此,对于您的示例,您可以使用一系列if
语句在分配各种数据时检查数据,并可能在else
部分中构建错误列表。
例如
string errorMessage = "";
string owner;
string owneremail;
if (props.ContainsKey("primary site owner"))
{
owner = props["primary site owner"].ToString();
}
else
{
errorMessage += "Primary Site Owner error";
}
if(props.ContainsKey("primary site owner Email"))
{
owneremail = props["primary site owner Email"].ToString();
}
else
{
errorMessage += "error with email";
}
etc...
答案 1 :(得分:2)
与上面提到的Steve一样,你应该在使用ToString()访问它之前检查props是否包含属性。为避免重复,您可以将检查分成另一种方法,例如(假设道具是字典):
private bool TryGetProperty(Dictionary<string, object> props, string key, out string val)
{
val = string.Empty;
if(props.ContainsKey(key))
{
val = props[key].ToString();
return true;
}
return false;
}
用法:
if(!TryGetProperty(props, "primary site owner", out owner))
{
Console.WriteLine("Error with site owner");
}
if(!TryGetProperty(props, "primary site owner email", out ownerEmail))
{
Console.WriteLine("Error with site owner email");
}
答案 2 :(得分:1)
您可以使用以下类进行验证:
public class ValidationResult
{
public ValidationResult()
{
MessagesList = new List<string>();
}
public bool Validated { get { return MessagesList.Count == 0; } }
public IList<string> MessagesList { get; set; }
public string Message
{
get
{
return string.Join(Environment.NewLine, MessagesList);
}
}
}
用法:
var validationResult = new ValidationResult();
if (props.ContainsKey("primary site owner"))
{
owner = props["primary site owner"].ToString();
}
else
validationResult.MessageList.Add("error with site owner");
if(props.ContainsKey("primary site owner Email"))
{
owneremail = props["primary site owner Email"].ToString();
}
else
validationResult.MessageList.Add("error with email");
...
if(!validationResult.Validated)
throw new Exception(validationResult.Message);
// or Console.WriteLine(validationResult.Message)