dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: How to use exception handling?

  1. #1
    Join Date
    Aug 2019
    Posts
    56

    How to use exception handling?

    I have a code which gets public IP address and one segment of code causes crash if not connected to internet. So I'm trying to apply exception handling, but I don't really understand how it works in this case, can you help me?

    HTML Code:
    #include <string.h>
    #include <winsock2.h>
    #include <windows.h>
    #include <iostream>
    #include <vector>
    #include <locale>
    #include <sstream>
    using namespace std;
    #pragma comment(lib,"ws2_32.lib")
    
    
    string website_HTML;
    locale local;
    void get_Website(string url);
    char lineBuffer[200][80] = { ' ' };
    char buffer[10000];
    char ip_address[16];
    int i = 0, bufLen = 0, j = 0, lineCount = 0;
    int lineIndex = 0, posIndex = 0;
    
    //****************************************************
    
    int main(void) {
    	cout << "\n\n\n";
    	try{
    	get_Website("api.ipify.org");
    	}
    	catch (const char* error)
    	{
    
    	}
    	for (size_t i = 0; i < website_HTML.length(); ++i) website_HTML[i] = tolower(website_HTML[i], local);
    
    	istringstream ss(website_HTML);
    	string stoken;
    
    	while (getline(ss, stoken, '\n')) {
    
    		//cout <<"-->"<< stoken.c_str() << '\n';
    
    		strcpy_s(lineBuffer[lineIndex], stoken.c_str());
    		int dot = 0;
    		for (int ii = 0; ii < strlen(lineBuffer[lineIndex]); ii++) {
    
    			if (lineBuffer[lineIndex][ii] == '.') dot++;
    			if (dot >= 3) {
    				dot = 0;
    				strcpy_s(ip_address, lineBuffer[lineIndex]);
    			}
    		}
    
    		lineIndex++;
    	}
    	cout << "Your IP Address is  " << ip_address << " \n\n";
    
    
    	cout << "\nPress ANY key to close.\n\n";
    	cin.ignore(); cin.get();
    
    	return 0;
    }
    
    //****************************************************
    
    void get_Website(string url) {
    	WSADATA wsaData;
    	SOCKET Socket;
    	SOCKADDR_IN SockAddr;
    	int lineCount = 0;
    	int rowCount = 0;
    	struct hostent *host;
    	string get_http;
    
    
    	get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";
    
    	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
    		cout << "WSAStartup failed.\n";
    		system("pause");
    		//return 1;
    	}
    
    	Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	host = gethostbyname(url.c_str());
    
    	SockAddr.sin_port = htons(80);
    	SockAddr.sin_family = AF_INET;
    	SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
    
    	if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
    		cout << "Could not connect";
    		system("pause");
    		//return 1;
    	}
    	send(Socket, get_http.c_str(), strlen(get_http.c_str()), 0);
    
    	int nDataLength;
    	while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
    		int i = 0;
    		while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
    
    			website_HTML += buffer[i];
    			i += 1;
    		}
    	}
    
    	closesocket(Socket);
    	WSACleanup();
    
    }

  2. #2
    Join Date
    Nov 2018
    Posts
    21

  3. #3
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,456

    Re: How to use exception handling?

    Quote Originally Posted by prako2 View Post
    I have a code which gets public IP address and one segment of code causes crash if not connected to internet. So I'm trying to apply exception handling, but I don't really understand how it works in this case, can you help me?
    ...
    Does this code compile?
    I don't see where your get_Website function throws the exception you are trying to catch...
    Victor Nijegorodov

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,816

    Re: How to use exception handling?

    As Victor states, get_Website() doesn't raise an exception - so catch() will never be executed.

    As in previous posts, you are not checking the return value from API functions for an error.

    This will be the cause of the 'crash'. For example, gethostbyname() returns NULL if it fails. if you don't check for this and then dereference the returned pointer you will get a 'crash'.

    I will re-iterate, for EVERY API call, you MUST ALWAYS check the return value for an error condition. The documentation for each API describes this.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.2.5)

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,063

    Re: How to use exception handling?


  6. #6
    Join Date
    Aug 2019
    Posts
    56

    Re: How to use exception handling?

    2kaud, thank you, I will keep that in mind.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)