2011-09-08 69 views
0

我創建客戶端服務器應用程序在Windows使用套接字,我想拋出異常在線程運行時如果發生任何問題,但我得到錯誤的拋出語句。異常,而線程拋出錯誤在scoket c + + windows

//create thread in cpp file 
    CreateThread(NULL,0,startServer,this,0,NULL); 

     //thread in header file 
      static unsigned long __stdcall startServer(void *i_SocketTransportServer) 
      { 
          ((SocketTransportServer*)i_SocketTransportServer)->StartServerThread(((SocketTransportServer *)i_SocketTransportServer)->m_socketServer); 
       return 0; 
      } 

     //and StartServerThread is function called by thread 
     // SocketTransportServer is inner class of RMLThinTransport 
      void RMLThinTransport::SocketTransportServer::StartServerThread(SOCKET i_socketServer) 
      { 
       m_socketAccept=NULL; 
       while(true) 
       { 
        Sleep(20); 
        if(m_canAcceptMore) 
        { 
         m_canAcceptMore=false; 
         if(!m_isRunning) 
         { 
           break; 
         } 
         try 
         { 
          m_socketAccept=accept(m_socketServer,NULL,NULL); 
          if(m_socketAccept==INVALID_SOCKET) 
          { 
           int lastError=WSAGetLastError(); 
           closesocket(m_socketAccept); 
                                  SocketExceptions           
exceptionInAcceptAtServer; 
            exceptionInAcceptAtServer.detectErrorAccept(&lastError); 

throw exceptionInAcceptAtServer; 
          } 
          else 
          { 
           //_LOG("Client connected",EventTypeInfo) ; 
           OutputDebugStringW(L"client connected....."); 
           /* If client connected then setClinetCout value 1 */ 
           setClientCount(1); 
           m_ClientSockets.push_back(m_socketAccept); 
           CreateThread(NULL,0,receiveDataAtServer,this,0,NULL); 
          } 

         } 
         catch(SocketExceptions& i_exceptionInAcceptAtServer) 
         { 

          /*OutputDebugStringW(L"Can't accept client In Exception. ."); */ 
    throw i_exceptionInAcceptAtServer;//getting runtime error from here 

         } 
        } 

       } 

      } 

現在我想在服務器關閉時拋出錯誤,但我得到運行時錯誤。所以有什麼辦法,所以我可以在我的主要function.sorry錯誤,但我是新的C++,所以請幫助我。和錯誤是

enter image description here

回答

0

拋出異常是沒有問題的代碼;這是缺少任何代碼趕上這個例外是這個問題。應用程序正在終止,因爲沒有任何東西可以捕捉你正在拋出的異常;你必須確保有一些東西能夠抓住它。您的startServer方法 - 線程過程 - 必須捕獲異常,並乾淨地退出線程。

+0

我想捕捉異常不在線程,但在這個線程的外側。 –

+0

你不能這樣做,異常不會從一個線程移動到另一個線程。他們解開這個單線程的堆棧,並且如果他們沒有被捕獲而觸頂,你的應用程序將被終止。你可以做的就是捕獲異常,並在你的catch塊中使用其他一些機制將問題傳達給應用程序的其餘部分。 –

+0

有沒有其他辦法? –