如何在服务器中引发异常并在客户端 c++ 中捕获它

How to throw an exception in server and catch it in client c++?

本文关键字:客户端 c++ 服务器 异常      更新时间:2023-10-16

我想知道我是否可以从服务器发送异常并在客户端中接收它。这是我的服务器:

void MyServer::on_new_message(int identifier, string message) {
    if(/*some condition for message*/)
      throw BadIO();
}

这是我客户的主要内容:

int main(){
try{
          cin>>c;
          socket.send(c);
          socket.receive();
        }
            catch(BadIO& exp)
        {
          cout<<exp.what()<<endl;
        }
    return 0;
    }

运行此代码后,我得到:

在抛出"BadIO"实例后终止调用 已中止(核心已转储)

提前致谢:)

这是可能的。

异常需要在服务器中序列化,就像在进程之间传递的任何其他对象一样。具有针对异常的特殊消息,以便socket.receive可以检测到它,反序列化异常并将其抛出到客户端中。