gpt4 book ai didi

c# - 如何返回到 try-catch C# 的 try block 中的下一条语句

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:02 25 4
gpt4 key购买 nike

在如下代码中:

假设我有一个 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...

关于c# - 如何返回到 try-catch C# 的 try block 中的下一条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com