C#WinForms尝试Catch在一个类中

时间:2014-03-08 11:28:24

标签: c# winforms exception exception-handling

我正在使用连接到互联网的服务引用,如果连接失败,我想在消息框中显示消息。如何在具有void返回类型的类的成员函数中调用消息框?这是该类的成员函数:

 public void ReverseGeocodePoint()
    {
        try{
        string results = "";
        string key = "abc";
        ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();

        // Set the credentials using a valid Bing Maps key
        reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
        reverseGeocodeRequest.Credentials.ApplicationId = key;

        // Set the point to use to find a matching address
        GeocodeService.Location point = new GeocodeService.Location();
        point.Latitude = latitude;
        point.Longitude = longitude;

        reverseGeocodeRequest.Location = point;

        // Make the reverse geocode request
        GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
        //This will connect to the server
        GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);

        if (geocodeResponse.Results.Length > 0)
            results = geocodeResponse.Results[0].DisplayName;
        else
            results = "No Results found";

        address = results;
    }} catch{ //here I want to show a msgbox but the problem is, this is not the form class}

1 个答案:

答案 0 :(得分:2)

如果那里没有什么可以解决的话,请不要在该课程中捕获异常。只是让它冒出来并抓住你可以做某事的地方:

public class MyForm : Form
{
    public void SomeMethod()
    {
        try
        {
            var sc = new ServiceClass();
            sc.ReverseGeocodePoint();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

ReverseGeocodePoint()中,删除try/catch语句。