C# 类中的异常处理

标签 c# exception class

C# 2008

我开发了下面的类(class)。我必须从 Web 服务器获取余额。完成后,它将返回我的主应用程序并返回结果。

但是,有时网络服务器会因某些未知原因而失败。可能是高流量或其他原因。但是,我还没有在我的类中实现任何异常处理。因为使用它的应用程序会处理异常。

但是,客户端已经确认,当网络服务器确实失败时,它会显示一个未处理的异常对话框。然后他们必须单击继续才能继续使用我的应用程序。

所以下面我不确定我是否应该在我的类中实现异常处理。但是,我很困惑为什么没有在我的应用程序中捕获异常,如下所示。

非常感谢您的任何建议,或者如果您发现任何其他错误,

private void OnGetBalanceCompleted(object sender, SIPPhoneLibraryEventArgs e)
    {
        try
        {
            //If the balance starts with 'null' there has been an error trying to get the balance.
            if (e.Balance.StartsWith("null"))
            {
                statusDisplay1.CurrentBalance = CATWinSIP_MsgStrings.BalanceError;
            }
            else
            {
                // Display the current balance and round to 2 decimal places.
                statusDisplay1.CurrentBalance = Math.Round(Convert.ToDecimal(e.Balance), 2).ToString();

                //If the balance is zero display in the status message
                if (decimal.Parse(e.Balance) == 0)
                {
                    this.statusDisplay1.CallStatus = "Zero Balance";
                }
            }
            //Remove the event as no longer needed
            siplibrary.GetBalanceCompletedEvent -= new EventHandler<SIPPhoneLibraryEventArgs>(OnGetBalanceCompleted);
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }




//Control library for all importing functions
public class Balance : IDisposable
{
    //Constructor
    WebClient wc;
    public Balance()
    {
        using (wc = new WebClient())
        {
            //Create event handler for the progress changed and download completed events
            wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
        }
    }

    ~Balance()
    {
        this.Dispose(false);
    }

    //Event handler and the method that handlers the event
    public EventHandler<SIPPhoneLibraryEventArgs> GetBalanceCompletedEvent;

    //The method that raises the event
    public void OnGetBalanceCompleted(SIPPhoneLibraryEventArgs e)
    {
        if (GetBalanceCompletedEvent != null)
        {
            GetBalanceCompletedEvent(this, e);
        }
    }

    //Get the current balance for the user that is logged in.
    //If the balance returned from the server is NULL display error to the user.
    //Null could occur if the DB has been stopped or the server is down.       
    public void GetBalance(string sipUsername)
    {
        //Remove the underscore ( _ ) from the username, as this is not needed to get the balance.
        sipUsername = sipUsername.Remove(0, 1);

        string strURL = string.Format("http://xxx.xxx.xx.xx:xx/voipbilling/servlet/advcomm.voipbilling.GetBalance?CustomerID={0}", sipUsername);

        //Download only when the webclient is not busy.
        if (!wc.IsBusy)
        { 
            // Sleep for 1/2 second to give the server time to update the balance.
            System.Threading.Thread.Sleep(500);
            // Download the current balance.
            wc.DownloadStringAsync(new Uri(strURL));
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Busy please try again");
        }
    }

    //return and display the balance after the download has fully completed
    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        //Pass the result to the event handler
        this.OnGetBalanceCompleted(new SIPPhoneLibraryEventArgs(e.Result));
    }

    //Progress state of balance.
    void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        //Write the details to the screen.
        Console.WriteLine(e.TotalBytesToReceive);
        Console.WriteLine(e.BytesReceived);
        Console.WriteLine(e.ProgressPercentage);
    }


    //Dispose of the balance object
    public void Dispose()
    {
        Dispose(true);

        GC.SuppressFinalize(this);
    }

    //Remove the event handlers
    private bool isDisposed = false;
    private void Dispose(bool disposing)
    {
        if (!this.isDisposed)
        {
            if (disposing)
            {
                wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

                wc.Dispose();
            }               
            isDisposed = true;
        }
    }
}

最佳答案

您似乎只在 OnGetBalanceCompleted 事件上捕获异常,而不是在获取余额的过程中捕获异常。

当提取出现任何错误时,甚至都不会调用 OnGetBalanceCompleted,这就是不调用异常处理程序的原因。

关于C# 类中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/796048/

相关文章:

c# - 尝试在非 HttpClient 套接字上进行操作

java - 为什么 RuntimeException 扩展 Exception 而不是其他方式?

android - 处理 Kotlin Coroutines 中自定义 okhttp 拦截器引发的异常

c++ - 内联 asm 跳转后抛出 C++ 异常

java - 尝试创建 fragment 类

c# - 如何在不同字符之间拆分字符串

c# - 在 C# 中使用扩展方法而不是实例方法的缺点

c# - GZipStream 和解压

php - 自定义 Composer 命名空间找不到类

ruby - 为什么嵌套类的行为在不同的类声明方式之间有所不同?