简体   繁体   中英

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
{
   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?

Basically I want this behavior below, but don't want 10 different try catch blocks.

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.

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.

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(). To avoid duplication, you can separate the checking into another method, something like (assume props is a dictionary):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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