首页 > 解决方案 > 无法正确处理我的代码中的异常

问题描述

这是一个小例程(我已经写了行号,因此更容易参考)我用于将数据从我的桌面应用程序传输到我的移动设备。它运行良好,但我无法正确处理异常。如果我写我的代码,因为它低于System.Net.Sockets.SocketException异常被处理但由于客户端无法连接这就是下一行(17)产生异常的原因

System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.

现在,如果我尝试将第 17 行和第 18 行放入尝试中,则会出现另一个错误,即流成为本地对象,因此第 24 行会产生错误。

如果我在开头声明流,那么第 24 行会出现另一个错误

ERROR :use of unassigned variable stream.

对我来说,这是一个僵局,我无法通过它。提前致谢!!

 C#

1 void  BluetoothClientConnectCallback(IAsyncResult result)
2        {
3                BluetoothClient client = (BluetoothClient)result.AsyncState;
4                Stream stream;
5
6                try
7                {
8                    client.EndConnect(result);
9                }
10
11                catch (System.Net.Sockets.SocketException)
12                {
13                   MessageBox.Show("Unable to connect to device!", "Error", 
                     MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
14                    
15                }
16
17                stream = client.GetStream();
18                stream.ReadTimeout = 1000;
19                  while (true)
20                  {
21                      while (!ready) ;
23                      message = Encoding.ASCII.GetBytes("{");
24                      stream.Write(message, 0, 1);
25                      ready = false;
26   
27                  } 

标签: c#exception

解决方案


好的,所以您的问题是try/catch没有涵盖正确的范围,应该是这样的:

void BluetoothClientConnectCallback(IAsyncResult result)
{       
    try
    {
        BluetoothClient client = (BluetoothClient)result.AsyncState;
        Stream stream;

        client.EndConnect(result);


        stream = client.GetStream();
        stream.ReadTimeout = 1000;
        while (true)
        {
            while (!ready) ;
            message = Encoding.ASCII.GetBytes("{");
            stream.Write(message, 0, 1);
            ready = false;

        }
    }

    catch (System.Net.Sockets.SocketException e)
    {
        MessageBox.Show($"Unable to connect to device with message:\r\n{e.Message}", "Error",
                   MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

    }
    catch (Exception ex)
    {
        //general exception catch, handle or ignore, but best is to log
    }
}

如果你想“隐藏”错误,那么你需要有一个空的捕获,但从不推荐

可能需要一些关于 try/catch 的阅读,查看这里

另外值得一提的是,当使用Streams最佳实践时,使用usingas 以确保正确处理它并且不会导致内存泄漏,例如:

void BluetoothClientConnectCallback(IAsyncResult result)
{
    try
    {
        BluetoothClient client = (BluetoothClient)result.AsyncState;    
        client.EndConnect(result);
        using (var stream = client.GetStream())
        {
            stream.ReadTimeout = 1000;
            while (true)
            {
                while (!ready) ;
                message = Encoding.ASCII.GetBytes("{");
                stream.Write(message, 0, 1);
                ready = false;
            }
        }
    }

    catch (System.Net.Sockets.SocketException e)
    {
        MessageBox.Show($"Unable to connect to device with message:\r\n{e.Message}", "Error",
                   MessageBoxButtons.OKCancel, MessageBoxIcon.Error);    
    }
    catch (Exception ex)
    {
        //general exception catch, handle or ignore, but best is to log
    }
}

还有一些关于处理来自另一个 SO 帖子的异常的提示here


推荐阅读