【问题标题】:.net Try Catch for sockets.net 尝试 Catch 获取套接字
【发布时间】:2017-09-15 17:07:12
【问题描述】:

MSDN 给出了排除网络错误的示例:

MyData md;

try {
    // Code that could throw an exception
    md = GetNetworkResource();
}
catch (const networkIOException& e) {
    // Code that executes when an exception of type
    // networkIOException is thrown in the try block
    // ...
    // Log error message in the exception object
    cerr << e.what();
}
catch (const myDataFormatException& e) {
    // Code that handles another exception type
    // ...
    cerr << e.what();
}

我正在将一段 C 代码转换为 C++,但不确定如何合并此代码:

if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR)
{

    fputs("\r\n WSAStartup failed", smtpfile);
    WSACleanup();
    return -1;
}

进入try catch块

C++ 新手,请原谅我的无知。提前感谢您的帮助。

【问题讨论】:

  • 第二个代码块中的任何内容都不会引发异常,因此相对于 try/catch 块而言,它的去向并不重要。但是第一个代码块中的那个例子很糟糕。如果GetNetworkResource(); 抛出异常,它允许md 被访问和未初始化的可能性。一个更好的例子是try { MyData md; // Code that could throw an exception md = GetNetworkResource(); } ,这样md 就不会在GetNetworkResource 失败的范围内。
  • 另外,当WSAStartup() 失败时调用WSACleanup() 是非常糟糕的,特别是如果WSAStartup() 之前已经被调用过。除非WSAStartup() 成功,否则不要调用WSACleanup()

标签: c++ .net sockets try-catch


【解决方案1】:

在这种情况下没有必要使用 try catch,除非您想在许多此类情况下重用处理部分。

最接近你想要做的是如下

MyData md;

try {
// Code that could throw an exception
    md = GetNetworkResource();

    if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR)
    {
      throw new myXYZException();
    }
}

catch (const networkIOException& e) {
   // Code that executes when an exception of type
   // networkIOException is thrown in the try block
   // ...
   // Log error message in the exception object
   cerr << e.what();
}
catch (const myDataFormatException& e) {
   // Code that handles another exception type
   // ...
   cerr << e.what();
}
catch(const myXYZException& e) {
    fputs("\r\n WSAStartup failed", smtpfile);
    WSACleanup();
    return -1;
}

除此之外,您还必须定义实现 IException 的 myXYZException 类

【讨论】:

  • myXYZException 处理程序根本不应该调用WSACleanup()。这是原始 C/C++ 代码中的错误。
  • 哦,是的,我们绝对可以确定调用 WSACleanup() 的更好地方。我只是在向 JTwine 解释 try catch 的概念
  • 并不总是需要实现从 IException 派生的自定义异常类。如果我们可以使用任何符合异常性质且尚未处理的标准异常;那么这也可以完成这项工作。
猜你喜欢
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多