c# - 无法正确处理我的代码中的异常
问题描述
这是一个小例程(我已经写了行号,因此更容易参考)我用于将数据从我的桌面应用程序传输到我的移动设备。它运行良好,但我无法正确处理异常。如果我写我的代码,因为它低于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 }
解决方案
好的,所以您的问题是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
最佳实践时,使用using
as 以确保正确处理它并且不会导致内存泄漏,例如:
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
推荐阅读
- c++ - 每个监视器 DPI 感知 MFC MDI 应用程序的问题
- android - api图像返回null
- javascript - javascript 将对象分组为 n 组
- powershell - 远程服务器在 Powershell 中运行 CMD
- java - If else 循环跳过 if 子句 [if(2 > 1) ] 并直接移动到 else 子句中的死代码。gRPC 实例化
- sql - 按日期加入表格正在删除我想保留的日期
- oracle - 在 Oracle 中添加两个列值
- r - 快速将对象从 JSON 转换为数据框
- shader - 执行简单平移和翻转时纹理边缘闪烁
- r - 我可以将 Google 电子表格下载为 CSV 而不是 HTML?