在如下代码中:
假设我有一个 try
上面有一堆单独的行,但第一行失败了,在我的 catch block 中我可以输出失败,有没有办法继续 try block 中的下一条语句?
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 block 中发出 resume
命令让它尝试设置 owneremail 吗?
基本上我想要下面的这种行为,但不想要 10 个不同的 try catch block 。
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 ...
为程序流使用 try-catch block 不是最佳实践,不应使用。
此外,您不应该依赖于捕获可以先检查并适当处理的错误。
因此对于您的示例,您可以使用一系列 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...
我是一名优秀的程序员,十分优秀!