我正在搜索我的数据库检查地址并使用Geocode找到lat/lng.一旦我点击一个空值的记录,它就会移动到catch.知道如何让它移动到下一个记录吗?
static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Data Source Here";
con.Open();
SqlDataReader reader;
try
{
reader = new SqlCommand("select PHAddress4, PHAddress5 from FLC_ProspectHeaderTable", con).ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(reader["PHAddress4"].ToString());
Console.WriteLine(reader["PHAddress5"].ToString());
var address = (reader["PHAddress5"].ToString());
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
var result = xdoc.Element("GeocodeResponse").Element("result");
var locationElement = result.Element("geometry").Element("location");
var lat = locationElement.Element("lat");
var lng = locationElement.Element("lng");
Console.WriteLine(lat);
Console.WriteLine(lng);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在循环内捕获异常:
while (reader.Read())
{
try
{
// do something
}
catch (Exception ex)
{
// examine the exception to see what went wrong
// if you can't continue, then "throw;"
// else...
continue;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,上面将是如何从异常中恢复以继续循环. 但是,也许我最初误解了这个问题.如果可以很容易地,有意义地避免异常摆在首位(也就是说,如果它不是一个真正的例外情况),那么这将是首选.考虑一下不应该使用异常来控制逻辑流的格言.
从逻辑上讲,如果你能够在执行导致异常的操作之前检查这个条件,那么代码的整体结构看起来会更像这样:
while (reader.Read())
{
// do something
if (someCondition)
{
// do the rest of the something
}
else
continue;
}
Run Code Online (Sandbox Code Playgroud)
(或者您可以反转条件以首先检查"继续"情况,这也很有效.这取决于您在代码中看起来更干净的东西.)
你的具体情况,这完全取决于什么导致它失败.例如,如果您的某个变量是null,那么您可以检查:
var result = xdoc.Element("GeocodeResponse").Element("result");
if (result == null)
continue;
Run Code Online (Sandbox Code Playgroud)
基本上,您需要确定代码中可能出现故障的内容,并引入一些逻辑条件以从该故障中恢复.理想情况下,循环的任何此类"继续"将在任何永久性副作用发生之前完成.在你的代码中,看起来唯一的永久副作用是写入控制台,所以我建议将所有这些放在循环体的最后.然后,当您检查条件时,您可以continue;在逻辑中遇到可继续故障状态.如果一切都通过,代码将到达写入控制台的行然后自然继续.