无法正确处理我的代码中的异常

时间:2019-06-21 07:21:07

标签: c# exception

这是一个小例程(我已经写了行号,因此将更易于参考),我必须将数据从桌面应用程序传输到移动设备。它运行正常,但是我无法正确处理异常。如果我在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                  } 

2 个答案:

答案 0 :(得分:3)

好的,所以您的问题是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进行一些阅读,请查看here

还值得一提的是,在使用Streams时,最佳实践是使用using,以确保其正确放置且不会引起内存泄漏,例如:

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中的异常的提示

答案 1 :(得分:1)

执行所有可能在try块内和catch内抛出异常的操作,您认为应该处理的异常。

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

  try
  {
    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)
  {
    MessageBox.Show("Unable to connect to device!", "Error",
    MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
  }
  catch (InvalidOperationException ex) 
  { 
     MessageBox.Show("Invalid operation exception!", "Error",
     MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
  }
  catch (Exception ex) 
  {
     MessageBox.Show("Exception thrown!", "Error",
     MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
  }
}