简体   繁体   English

如何返回try捕获C#的try块中的下一条语句

[英]How do I return to next statement in try block for try-catch C#

In Code such as the following: 在如下代码中:

Say I have a try with a bunch of separate lines on it and the first one fails, in my catch block I can output the failure, is there a way to continue to the next statement in the try block? 假设我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");
}

For example if it fails to set owner, can I issue a resume command in the catch block to have it try to set owneremail next? 例如,如果无法设置所有者,是否可以在catch块中发出resume命令以使其接下来尝试设置owneremail?

Basically I want this behavior below, but don't want 10 different try catch blocks. 基本上,我希望这种行为在下面,但不要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 ...  

Using try-catch blocks for program flow is not best practice and shouldn't be used. 在程序流中使用try-catch块不是最佳实践,不应使用。

Additionally, you shouldn't be relying on catching an error that you could check for first and handle appropriately. 此外,您不应该依赖于捕获可以首先检查并适当处理的错误。

So for your example, you could use a series of if statements to check the data as you are assigning the various, and maybe build up a list of errors in the else part. 因此,对于您的示例,可以在分配各种变量时使用一系列if语句检查数据,并可能在else部分中建立错误列表。

Eg. 例如。

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...

Like Steve mentioned above, you should check whether props contains the property before accessing it using ToString(). 像上面提到的Steve一样,您应该在使用ToString()访问属性之前检查props是否包含该属性。 To avoid duplication, you can separate the checking into another method, something like (assume props is a dictionary): 为了避免重复,您可以将检查分成另一种方法,例如(假设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;
}

Usage: 用法:

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");
}

You can use following class for validation: 您可以使用以下类进行验证:

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);
        }
    }
}

Usage: 用法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM